using System.Runtime.InteropServices;
using System.Security.Principal;
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext m_ImpersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private bool ImpersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
m_ImpersonationContext = tempWindowsIdentity.Impersonate();
if (m_ImpersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
private void UndoImpersonation()
{
m_ImpersonationContext.Undo();
}
// Use
if (ImpersonateValidUser([USERID], [DOMAIN], [PASSWORD]))
{
.....
UndoImpersonation();
}
'Dev::ASP.NET,C#' 카테고리의 다른 글
Global.asax 의 Application_Error를 통한 에러 처리 (0) | 2012.06.13 |
---|---|
Page클래스의 이벤트 리스트 (0) | 2012.06.12 |
C#에서 SizeOf (0) | 2012.05.31 |
C#에서 JSON (0) | 2012.05.25 |
C# 문자열 관련 (0) | 2011.03.29 |