【问题标题】:Impersonate user in codebehind在代码隐藏中模拟用户
【发布时间】:2011-05-29 03:51:26
【问题描述】:

我想在代码中模拟特定用户,以便在远程机器上执行一些文件操作。我遇到的问题是我无法模拟工作。我正在使用此处找到的 Microsoft 文章中的代码: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:

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

我用 myUserName、myDomain 和 myPassword 替换了帖子的真实凭据。

Web 服务器是运行 IIS 7 的 Windows 2008 服务器。我不是服务器专家,所以我不知道在哪里进行故障排除过程。是代码问题还是服务器端的问题?

与往常一样,提前感谢您抽出宝贵时间提供帮助!

【问题讨论】:

  • 是否抛出了未处理的异常或者它只是失败了?事件日志中有任何内容吗?
  • +100 个混淆点,用于将 DLL 函数导入与 VB 混合。您尝试过 C#吗?
  • 您有机会查看我的答案吗?我很好奇它是否对你有用。

标签: asp.net vb.net impersonation


【解决方案1】:

这是我在生产中使用的代码。

首先是班级,和你的很相似:

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

【讨论】:

  • 我不知道为什么我没有在收件箱中看到回复。抱歉耽搁了。
  • 我需要在 Web 应用程序上接收文件并将其上传到需要身份验证的共享文件夹。这门课效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
相关资源
最近更新 更多