Skip to content

Commit

Permalink
Update LogonUser. Fixes #2.
Browse files Browse the repository at this point in the history
  • Loading branch information
mattjohnsonpint committed Oct 8, 2013
1 parent 046cc9b commit 95f9144
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
4 changes: 3 additions & 1 deletion SimpleImpersonation/Impersonation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ public static Impersonation LogonUser(string domain, string username, string pas

private Impersonation(string domain, string username, string password, LogonType logonType)
{
var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out _handle);
IntPtr handle;
var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle);
if (!ok)
{
var errorCode = Marshal.GetLastWin32Error();
throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode));
}

_handle = new SafeTokenHandle(handle);
_context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
}

Expand Down
2 changes: 1 addition & 1 deletion SimpleImpersonation/NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace SimpleImpersonation
internal class NativeMethods
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
Expand Down
10 changes: 7 additions & 3 deletions SimpleImpersonation/SafeTokenHandle.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
using Microsoft.Win32.SafeHandles;
using System;
using Microsoft.Win32.SafeHandles;

namespace SimpleImpersonation
{
internal sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true) { }
internal SafeTokenHandle(IntPtr handle)
: base(true)
{
this.handle = handle;
}

protected override bool ReleaseHandle()
{
Expand Down

0 comments on commit 95f9144

Please sign in to comment.