Search code examples
c#authenticationprincipalcontext

What is Impersonation and how does it work with PrincipalContext


I need to logon a user on my application verifying his credentials. I found the old LogonUser API and the new PrincipalContext object. I'd really like to use the PrincipalContext because it's easy and smart, but I know that usign LogonUser you can get a token to use for Impersonating user? What exactly is impersonation? Is there a way to do the same thing using the PrincipalContext?

Thank you


Solution

  • You would typically use impersonation if you need to execute your application as a different user (usually with more/specific access) than the one is currently logged in.

    The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.

    If you need to authenticate a user and validate credentials, you can use PrincipalContext.

    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
    {
       bool auth = ctx.ValidateCredentials(username,password); 
    }