2011-10-10 2 views
9
WindowsIdentity identity = new WindowsIdentity(accessToken); 
WindowsImpersonationContext context = identity.Impersonate(); 

... 
context.Undo(); 

어디에서 Administraotr UserName과 Passowrd를 선언합니까?사용자 이름과 암호로 가장 할 수 있습니까?

accessToken PARAM 너무 많이 저를 도움이되지 않습니다 ...

내가 그것을 위해 DLL의를 가져해야합니까?

답변

22

당신은 사용자의 토큰을 얻을 필요가 c#

외부 메서드 선언에서 여기) 를, C#으로 상상.

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

예 :

IntPtr userToken = IntPtr.Zero; 

bool success = External.LogonUser(
    "john.doe", 
    "domain.com", 
    "MyPassword", 
    (int) AdvApi32Utility.LogonType.LOGON32_LOGON_INTERACTIVE, //2 
    (int) AdvApi32Utility.LogonProvider.LOGON32_PROVIDER_DEFAULT, //0 
    out userToken); 

if (!success) 
{ 
    throw new SecurityException("Logon user failed"); 
} 

using (WindowsIdentity.Impersonate(userToken)) 
{ 
    // do the stuff with john.doe's credentials 
} 
+0

가 암호없이 그렇게 할 수있는 방법이있는 advapi32.dll의에서 LogonUser를 호출 /는 P를 사용? 내가 가장 (impersonation) 직전에 만들고있는 것처럼 접근 할 수 있습니다. 단지 물어볼 것이라고 생각했습니다. – Doug

+2

"CloseHandle"을 호출해야합니다 (LogonUser'에 대한 [docs]에서 언급 한 것처럼) (https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184 (v = vs.85) .aspx))를 사용하는 블록 이후의 'userToken'에 대해. 또는 이것이 'WindowsIdentity'에 의해 어떤 식 으로든 불려지나요? – CodeFox

+0

안녕하세요 이것이 ASP.NET 응용 프로그램 인 경우이 범위는 무엇입니까? 모든 페이지에서이 함수를 호출해야합니까? –

2

LogonUser() API를 P/호출해야합니다. 그것은 사용자 이름, 도메인 및 암호를 받아들이고 토큰을 반환합니다.

5

정확하게 사용해야합니다. 그것을 얻으려면 LogonUser 메소드를 호출해야합니다 :

oops는 단지 VB.net 코드를 가지고 있다는 것을 깨닫지 못했습니다.

Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _ 
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _ 
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _ 
ByRef phToken As IntPtr) As Boolean 

및 실행을 :

_Token = New IntPtr(0) 

Const LOGON32_PROVIDER_DEFAULT As Integer = 0 
'This parameter causes LogonUser to create a primary token. 
Const LOGON32_LOGON_INTERACTIVE As Integer = 2 
Const LOGON32_LOGON_NEWCREDENTIALS As Integer = 9 

_Token = IntPtr.Zero 

' Call LogonUser to obtain a handle to an access token. 
Dim returnValue As Boolean = LogonUser(_User, _Domain, _Password, LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, _Token) 

If False = returnValue Then 
    Dim ret As Integer = Marshal.GetLastWin32Error() 
    Console.WriteLine("LogonUser failed with error code : {0}", ret) 
    Throw New System.ComponentModel.Win32Exception(ret) 
End If 

_Identity = New WindowsIdentity(_Token) 
_Context = _Identity.Impersonate()