Pages

Friday, July 24, 2009

Tip of the Day: MicrosftWord and Impersonation

Here's a useful tip....

If you're using the Microsoft.Office.Interop.Word assembly in your asp.net application, before you begin using the API via code, you must impersonate the current user. Below are two examples on how to impersonate in ASP.NET:

Setting impersonation through configuration settings:
Add the following code highlighted under the system.web element.

Setting impersonation through code:
Right before you being to instantiate Microsoft Word classes such as Application or Document, add the following code in red:
WindowsIdentity iUser = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext wic = iUser.Impersonate();
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

The reason why you have to impersonate is because your ASP.NET application runs under the network service account and normally the network service account is not a valid user under Micrsoft Word. Because of this, you must impersonate a trusted(valid) user in order use the Microsoft Word assembly via code.

Enjoy!!

No comments:

Post a Comment