views:

1977

answers:

3

Is there a simple out of the box way to impersonate a user in .NET? So far i have been using this class from code project for all my impersonation requirements. But is there a better way to do it,by using .NET framework, out of the box? I have a user credential set, (username, password, domain name) which represents the identity i need to impersonate.

+7  A: 

Here is some good overview of .NET impersonation concepts.

Basically you will be leveraging these classes that are out of the box in the .NET framework:

The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.

spoon16
+3  A: 

I am putting some links here. if you feel it is not appropriate for your case, feel free to comment.

How to implement impersonation in an ASP.NET application

Would also recommend this post from Keith Brown.

Gulzar
+3  A: 

This is probably what you want:

using System.Security.Principal;
using(WindowsIdentity.GetCurrent().Impersonate())
{
     //your code goes here
}

But I really need more details to help you out. You could do impersonation with a config file (if you're trying to do this on a website), or through method decorators (attributes) if it's a WCF service, or through... you get the idea.

Also, if we're talking about impersonating a client that called a particular service (or web app), you need to configure the client correctly so that it passes the appropriate tokens.

Finally, if what you really want do is Delegation, you also need to setup AD correctly so that users and machines are trusted for delegation.

Edit:
Take a look here to see how to impersonate a different user, and for further documentation.

Esteban Araya
This code looks like it can impersonate only the Current windows Identity. Is there a way to get the WindowsIdentity object of another user?
ashwnacharya