Windows Avatars and Duplicate Tokens

I have an asp.net project where a request will delegate work to the background (via quartz.net). The web application uses Windows authentication and impersonation.

I would also like to impersonate the current user in the background thread. I read how to impersonate a user with the provided domain name, username and password and invoke the kernel. This method works.

IntPtr token;
var successfullLogon = LogonUser(userName, password, domain, logonType, logonProvider, out token);
if(successfullLogon == false)
{
    var errorCode = Marshal.GetHRForLastWin32Error();
    Marshal.ThrowExceptionForHR(errorCode);
}

This works, but it requires either a specific username / password or a user password. none of them are perfect.

I would like to transfer the token from the user ID from the request to the background and then impersonate the user from this existing token. I read that I should be able to call DuplicateHandle,

var token = ((WindowsIdentity)Request.User.Identity).GetToken().ToInt64();
var token = new IntPrt(token from request);
IntPtr duplicate;
try
{
    if(NaviteMethod.DuplicateToken(token, SecurityImpersonationLevel.Impersonate, out duplicate) == false)
    {
        var errorCode = Marshal.GetHRForLastWin32Error();
        Marshal.ThrowExceptionForHR(errorCode);
    }

    using(var identity = new WindowsIdentity(duplicate))
    using(var context = identity.Impersonate())
    {
        //do work
        context.Undo();
    }
}
finally
{
    if(duplicate != IntPtr.Zero)
    {
        NaviteMethod.CloseHandler(duplicate);
    }
}

. Overlapped I/O.

NativeMethod : , Microsoft.Win32.RegistryKey.OpenRemoteBaseKey() ?

? , - , ?

+5
1

, "LogonUser". ASP.NET. , .

+1

All Articles