messedupfir
messedupfir

Reputation: 127

asp.net WindowsIdentity Impersonate from known credentials C#

Good morning,

I have an asp.net project where a form (Authentication is set to None) validates the user credentials against a third party server and then upon validation, redirects the user to the protected content.

What I would like to do is create a WindowsIdentity from these credentials so that I can access other WindowsAuthentication pages on my server and also other pages on the network.

Is this possible?

Upvotes: 0

Views: 4971

Answers (1)

Fabio
Fabio

Reputation: 3120

You'll need to use the LogonUser API function to impersonate your calls (and you will need the account login and password too, so you can use this function).

Take a look at this article, it explains how to do it: http://msdn.microsoft.com/en-us/library/ff647404.aspx.

Here's a code snippet from this article, just to have an idea about this approach.

    try
    {
        // Create a token for DomainName\Bob
        // Note: Credentials should be encrypted in configuration file
        bool result = LogonUser("Bob", "DomainName",
                                "P@ssw0rd",
                                LogonSessionType.Network,
                                LogonProvider.Default,
                                out token);
        if (result)
        {
            WindowsIdentity id = new WindowsIdentity(token);

            // Begin impersonation
            impersonatedUser = id.Impersonate();
            // Log the new identity
            Response.Write(String.Format(
                           "</p>Identity after impersonation: {0}<br>",
                           WindowsIdentity.GetCurrent().Name));
            // Resource access here uses the impersonated identity
        }
        else
        {
            Response.Write("</p>LogonUser failed: " +
                           Marshal.GetLastWin32Error().ToString());
        }
    }
    catch
    {
        // Prevent any exceptions that occur while the thread is 
        // impersonating from propagating
    }
    finally
    {
        // Stop impersonation and revert to the process identity
        if (impersonatedUser != null)
            impersonatedUser.Undo();
        // Free the token
        if (token != IntPtr.Zero)
            CloseHandle(token);
    }

Upvotes: 1

Related Questions