WindowsIdentity constructor throws exception with token from LogonUser

3.1k views Asked by At

I'm running inside a command line application that authenticates users using LogonUser. The function returns correctly and fails correctly (invalid user name or password). When I pass the token returned by the LogonUser function into the WindowsIdentity(IntPtr) constructor, I receive the error:

Invalid token for impersonation - it cannot be duplicated.

I've tried duplicating the token before passing it into the WindowsIdentity constructor using the DuplicateToken function. This fails as well. I have UAC on and am running Windows 7 x64. Running as both admin and not admin yields the same result.

Some additonal info:

  • Logging into a domain
  • Using LOGON32_LOGON_INTERACTIVE
  • Using LOGON32_PROVIDER_DEFAULT
3

There are 3 answers

1
Adam Driscoll On BEST ANSWER

This ended up being environmental. DNS issue while attempting to authenticate against the domain. A reset of the development box fixed the issue.

0
Jeremy Gray On

Does the following work for you, or recreate the issue?

[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

// ...

IntPtr token;
LogonUser(Username, Domain, Password, 8, 0, out token)

WindowsIdentity wi;
wi = new WindowsIdentity(token);
1
BogdanRB On

I had the same error only in code compiled using in .Net Framework 4. There was no error when compiled with all previous versions.

this code used to fail in .net 4:

using(WindowsIdentity identity = new WindowsIdentity(accessToken))
    context = identity.Impersonate();

However, I found that this works:

context = WindowsIdentity.Impersonate(accessToken);