2010-12-22 4 views
7

원격 컴퓨터에서 일부 파일 조작을 수행하기 위해 특정 사용자를 코드로 가장하고 싶습니다. 문제는 내가 가장을 사귈 수 없다는 것입니다. 여기에있는 마이크로 소프트 기사의 코드를 사용하고 있습니다 : How to implement impersonation in an ASP.NET application코드 숨김으로 사용자 가장

어떻게 디버깅 프로세스를 시작해야하는지에 대한 지침을 원합니다. 여기 내 파일은 다음과 같습니다

에서 Test.aspx :

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="TraceFile_Test" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
    This is the test page!<br /> 
    <br /> 
    Result: <asp:Label ID="lblResult" runat="server"></asp:Label><br /> 
    <br /> 
    <asp:Button ID="btnRunTest" Text="Run Test" runat="server" /> 
    </div> 
    </form> 
</body> 
</html> 

Test.aspx.vb : 나는 대한 MyUserName 에다, MYDOMAIN 및 myPassword와 실제 자격 증명을 대체

Imports System.Web 
Imports System.Web.Security 
Imports System.Security.Principal 
Imports System.Runtime.InteropServices 

Partial Class TraceFile_Test 
    Inherits System.Web.UI.Page 


    Dim LOGON32_LOGON_INTERACTIVE As Integer = 2 
    Dim LOGON32_PROVIDER_DEFAULT As Integer = 0 

    Dim impersonationContext As WindowsImpersonationContext 

    Declare Function LogonUserA 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 Integer 

    Declare Auto Function DuplicateToken Lib "advapi32.dll" (_ 
          ByVal ExistingTokenHandle As IntPtr, _ 
          ByVal ImpersonationLevel As Integer, _ 
          ByRef DuplicateTokenHandle As IntPtr) As Integer 

    Declare Auto Function RevertToSelf Lib "advapi32.dll"() As Long 
    Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long 


    Public Sub Page_Load(ByVal s As Object, ByVal e As EventArgs) 
     lblResult.Text = "Hit button to run test, please." 
    End Sub 

    Private Function impersonateValidUser(ByVal userName As String, _ 
    ByVal domain As String, ByVal password As String) As Boolean 

     Dim tempWindowsIdentity As WindowsIdentity 
     Dim token As IntPtr = IntPtr.Zero 
     Dim tokenDuplicate As IntPtr = IntPtr.Zero 
     impersonateValidUser = False 

     If RevertToSelf() Then 
      If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then 
       If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then 
        tempWindowsIdentity = New WindowsIdentity(tokenDuplicate) 
        impersonationContext = tempWindowsIdentity.Impersonate() 
        If Not impersonationContext Is Nothing Then 
         impersonateValidUser = True 
        End If 
       End If 
      End If 
     End If 
     If Not tokenDuplicate.Equals(IntPtr.Zero) Then 
      CloseHandle(tokenDuplicate) 
     End If 
     If Not token.Equals(IntPtr.Zero) Then 
      CloseHandle(token) 
     End If 
    End Function 

    Private Sub undoImpersonation() 
     impersonationContext.Undo() 
    End Sub 


    Protected Sub btnRunTest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRunTest.Click 
     If impersonateValidUser("myUserName", "myDomain", "myPassword") Then 
      'Insert your code that runs under the security context of a specific user here. 
      Trace.Write("impersonation successful!") 
      lblResult.Text = "success" 
      undoImpersonation() 
     Else 
      'Your impersonation failed. Therefore, include a fail-safe mechanism here. 
      Trace.Write("impersonation failed!") 
      lblResult.Text = "fail" 
     End If 
    End Sub 
End Class 

게시하다.

웹 서버는 IIS 7을 실행하는 Windows 2008 서버입니다. 서버 사용자가 아니므로 어디에서 문제 해결 프로세스를 수행 할 것인지 잘 모릅니다. 코드 또는 서버 측의 문제입니까?

언제나 도움을 주셔서 감사드립니다.

+0

던져 처리되지 않은 예외가 아니면 그냥 실패 하는가? 이벤트 로그의 내용은 무엇입니까? – kd7

+0

VB에서 DLL 함수 가져 오기를 혼합하기위한 100 개의 혼란 지점. ** ** C# 시도 했습니까? –

+0

내 대답을 확인할 기회가 있었습니까? 그것이 당신을 위해 작동한다면 나는 궁금 하네. – Peter

답변

9

다음은 프로덕션에서 사용하는 코드입니다.

먼저 클래스, 당신과 매우 유사합니다 :

Imports System.Security.Principal 
Imports System.Security.Permissions 
Imports System.Diagnostics 
Imports System.Runtime.InteropServices 
Imports System.Security 

Public Class LogonAPI 
    Public Const SECURITY_IMPERSONATION_LEVEL_SecurityAnonymous As Integer = 0 
    Public Const SECURITY_IMPERSONATION_LEVEL_SecurityIdentification As Integer = 1 
    Public Const SECURITY_IMPERSONATION_LEVEL_SecurityImpersonation As Integer = 2 
    Public Const SECURITY_IMPERSONATION_LEVEL_SecurityDelegation As Integer = 3 

    Public Const LOGON32_PROVIDER_DEFAULT As Integer = 0 
    Public Const LOGON32_PROVIDER_WINNT35 As Integer = 1 
    Public Const LOGON32_PROVIDER_WINNT40 As Integer = 2 
    Public Const LOGON32_PROVIDER_WINNT50 As Integer = 3 

    Public Const LOGON32_LOGON_INTERACTIVE As Integer = 2 
    Public Const LOGON32_LOGON_NETWORK As Integer = 3 
    Public Const LOGON32_LOGON_BATCH As Integer = 4 
    Public Const LOGON32_LOGON_SERVICE As Integer = 5 
    Public Const LOGON32_LOGON_UNLOCK As Integer = 7 
    Public Const LOGON32_LOGON_NETWORK_CLEARTEXT As Integer = 8 
    Public Const LOGON32_LOGON_NEW_CREDENTIALS As Integer = 9 

    Public Const ERROR_LOGON_FAILURE As Integer = 1326 

    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _ 
    Public Shared Function LogonUser(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 
    End Function 

    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _ 
    Public Shared Function RevertToSelf() As Boolean 
    End Function 

    <DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _ 
    Public Shared Function CloseHandle(ByVal handle As IntPtr) As Boolean 
    End Function 

    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _ 
    Public Shared Function DuplicateToken(ByVal hToken As IntPtr, ByVal impersonationLevel As Integer, ByRef hNewToken As IntPtr) As Integer 
    End Function 

    Public Shared Function Login(ByVal Username As String, ByVal Domain As String, ByVal Password As String) As WindowsIdentity 
     Dim secPerm As New SecurityPermission(SecurityPermissionFlag.UnmanagedCode) 
     secPerm.Assert() 

     Dim user As WindowsIdentity = Nothing 

     Dim refToken As IntPtr = IntPtr.Zero 
     Dim loggedIn As Boolean 

     loggedIn = LogonAPI.LogonUser(Username, Domain, Password, LogonAPI.LOGON32_LOGON_NETWORK_CLEARTEXT, LogonAPI.LOGON32_PROVIDER_DEFAULT, refToken) 

     If loggedIn = True Then 
      user = New WindowsIdentity(refToken, "NTLM", WindowsAccountType.Normal, True) 
     End If 
     CodeAccessPermission.RevertAssert() 

     Return user 
    End Function 
End Class 

내가 호출하여 테스트 :

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    Dim ident As WindowsIdentity = LogonAPI.Login("user", "Domain", "password") 

    Dim imp = ident.Impersonate() 

    'impersonation code 
    Response.Write("Impersonating") 

    imp.Undo() 
End Sub 
+0

내받은 편지함에서 응답을 보지 못한 이유를 알 수 없습니다. 지연 돼서 죄송합니다. – zeroef

+0

웹 응용 프로그램에서 파일을 받고 인증이 필요한 공유 폴더에 파일을 업로드해야했습니다. 이 수업은 꽤 잘 진행되었습니다. – ASalazar