C# 如果我有用户名和密码,如何使用其他身份在asp.net中执行代码

C# 如果我有用户名和密码,如何使用其他身份在asp.net中执行代码,c#,asp.net,security,wmi,C#,Asp.net,Security,Wmi,我正在构建一个基于web的小型管理应用程序。 在它里面,我需要通过wmi连接到使用不同帐户的不同服务器 我想告诉我的应用程序:你现在由user1运行,做这个和这个。 然后我想告诉它:现在你是user2,做这个和这个 我想,我对我的问题不是很清楚,我会重构它。你必须编写一段单独的.Net代码(也有一些人工调用)来模拟你的用户,然后在模拟该用户的同时调用你的代码。之后,您可以恢复用户帐户: 为VB示例道歉,但这很容易移植到C# VB示例 公共类用户模拟 私有声明自动函数LogonUser Lib“

我正在构建一个基于web的小型管理应用程序。 在它里面,我需要通过wmi连接到使用不同帐户的不同服务器

我想告诉我的应用程序:你现在由user1运行,做这个和这个。 然后我想告诉它:现在你是user2,做这个和这个


我想,我对我的问题不是很清楚,我会重构它。

你必须编写一段单独的.Net代码(也有一些人工调用)来模拟你的用户,然后在模拟该用户的同时调用你的代码。之后,您可以恢复用户帐户:

为VB示例道歉,但这很容易移植到C#


VB示例
公共类用户模拟
私有声明自动函数LogonUser Lib“advapi32.dll”(ByVal lpszUsername为[String]_
ByVal LPSZ域为[String],ByVal LPSZ密码为[String]_
ByVal dwLogonType为整数,ByVal dwLogonProvider为整数_
ByRef phToken作为IntPtr)作为布尔值
_
私有共享函数FormatMessage(ByVal dwFlags为整数,ByRef lpSource为IntPtr_
ByVal dwMessageId为整数,ByVal dwLanguageId为整数,ByRef lpBuffer为[String]_
ByVal nSize为整数,ByRef参数为IntPtr)为整数
端函数
私有将自动函数CloseHandle Lib“kernel32.dll”(ByVal句柄为IntPtr)声明为布尔值
私有声明自动函数DuplicateToken Lib“advapi32.dll”(ByVal ExistingTokenHandle作为IntPtr_
ByVal安全性\u模拟\u级别为整数_
ByRef DuplicateTokenHandle(作为IntPtr)作为布尔值
_
作为WindowsImpersonationContext的公共共享函数ImpersonateUser(ByVal strDomain作为字符串,ByVal strUserid作为字符串,ByVal strPassword作为字符串)
将令牌句柄设置为新的IntPtr(0)
Dim dupeTokenHandle作为新IntPtr(0)
尝试
'使用获取指定用户、域和密码的用户令牌
'非托管LogonUser方法。
'本地计算机名可用于域名以模拟此计算机上的用户。
Const LOGON32\u PROVIDER\u默认为整数=0
'此参数导致LogonUser创建主令牌。
Const LOGON32\u LOGON\u INTERACTIVE As Integer=2
tokenHandle=IntPtr.Zero
'调用LogonUser以获取访问令牌的句柄。
Dim returnValue为Boolean=LogonUser(strUserid、strDomain、strPassword、LOGON32\u LOGON\u INTERACTIVE、LOGON32\u PROVIDER\u DEFAULT、tokenHandle)
如果returnValue=False,则
Dim ret As Integer=Marshal.GetLastWin32Error()
抛出新System.ComponentModel.Win32Exception(ret)
其他的
'使用LogonUser返回的令牌句柄。
将newId设置为新的WindowsIdentity(令牌句柄)
Dim ImpersonatedUser作为WindowsImpersonationContext=newId.Impersonate()
返回模拟用户
如果结束
特例
Console.WriteLine(“发生UserImpersonation.impersonateUser异常:”+ex.Message)
一无所获
结束尝试
“释放代币。
如果不是System.IntPtr.op_相等(tokenHandle,IntPtr.Zero),则
CloseHandle(令牌句柄)
如果结束
端函数
作为布尔值的公共共享函数UndoImpersonate(ByVal WIC作为WindowsImpersonationContext)
尝试
'停止模拟用户。
WIC.Undo()
返回真值
特例
Console.WriteLine((“发生异常。”+ex.Message))
返回错误
结束尝试
端函数
末级

您必须编写一段单独的.Net代码(也有一些人工调用)来模拟您的用户,然后在模拟该用户的同时调用您的代码。之后,您可以恢复用户帐户:

为VB示例道歉,但这很容易移植到C#


VB示例
公共类用户模拟
私有声明自动函数LogonUser Lib“advapi32.dll”(ByVal lpszUsername为[String]_
ByVal LPSZ域为[String],ByVal LPSZ密码为[String]_
ByVal dwLogonType为整数,ByVal dwLogonProvider为整数_
ByRef phToken作为IntPtr)作为布尔值
_
私有共享函数FormatMessage(ByVal dwFlags为整数,ByRef lpSource为IntPtr_
ByVal dwMessageId为整数,ByVal dwLanguageId为整数,ByRef lpBuffer为[String]_
ByVal nSize为整数,ByRef参数为IntPtr)为整数
端函数
私有将自动函数CloseHandle Lib“kernel32.dll”(ByVal句柄为IntPtr)声明为布尔值
私有声明自动函数DuplicateToken Lib“advapi32.dll”(ByVal ExistingTokenHandle作为IntPtr_
ByVal安全性\u模拟\u级别为整数_
ByRef DuplicateTokenHandle(作为IntPtr)作为布尔值
_
作为WindowsImpersonationContext的公共共享函数ImpersonateUser(ByVal strDomain作为字符串,ByVal strUserid作为字符串,ByVal strPassword作为字符串)
将令牌句柄设置为新的IntPtr(0)
Dim dupeTokenHandle作为新IntPtr(0)
尝试
'使用获取指定用户、域和密码的用户令牌
'非托管LogonUser方法。
'本地计算机名可用于域名以模拟此计算机上的用户。
Const LOGON32\u PROVIDER\u默认为整数=0
'此参数导致LogonUser创建主令牌。
Const LOGON32\u LOGON\u INTERACTIVE As Integer=2
tokenHandle=IntPtr.Zero
'调用LogonUser以获取访问令牌的句柄。
Dim returnValue为Boolean=LogonUser(strUserid、strDomain、strPassword、LOGON32
Public Class UserImpersonation

    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

    <DllImport("kernel32.dll")> _
    Private Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
        ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
        ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer

    End Function

    Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

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

    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
    Public Shared Function ImpersonateUser(ByVal strDomain As String, ByVal strUserid As String, ByVal strPassword As String) As WindowsImpersonationContext

        Dim tokenHandle As New IntPtr(0)
        Dim dupeTokenHandle As New IntPtr(0)

        Try
            ' Get the user token for the specified user, domain, and password using the 
            ' unmanaged LogonUser method.  
            ' The local machine name can be used for the domain name to impersonate a user on this machine.

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

            tokenHandle = IntPtr.Zero

            ' Call LogonUser to obtain a handle to an access token.
            Dim returnValue As Boolean = LogonUser(strUserid, strDomain, strPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)

            If returnValue = False Then
                Dim ret As Integer = Marshal.GetLastWin32Error()
                Throw New System.ComponentModel.Win32Exception(ret)
            Else
                ' Use the token handle returned by LogonUser.
                Dim newId As New WindowsIdentity(tokenHandle)
                Dim ImpersonatedUser As WindowsImpersonationContext = newId.Impersonate()

                Return ImpersonatedUser
            End If

        Catch ex As Exception
            Console.WriteLine("UserImpersonation.impersonateUser Exception Occurred: " + ex.Message)

            Return Nothing
        End Try

        ' Free the tokens.
        If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then
            CloseHandle(tokenHandle)
        End If
    End Function


    Public Shared Function UndoImpersonate(ByVal WIC As WindowsImpersonationContext) As Boolean
        Try
            ' Stop impersonating the user.
            WIC.Undo()

            Return True
        Catch ex As Exception
            Console.WriteLine(("Exception occurred. " + ex.Message))

            Return False
        End Try

    End Function
End Class