我需要在vb.net 2008 winforms应用程序中“模拟”用户,以便应用程序可以接受PC上任何用户的Active Directory登录,而不管实际登录到Windows的用户是谁。我希望应用程序的.user是登录到应用程序的人的广告帐户。我用以下代码成功地完成了此操作:
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
Const LOGON32_LOGON_INTERACTIVE As Long = 2
Const LOGON32_LOGON_NETWORK As Long = 3
Const LOGON32_PROVIDER_DEFAULT As Long = 0
Const LOGON32_PROVIDER_WINNT35 As Long = 1
Const LOGON32_PROVIDER_WINNT40 As Long = 2
Const LOGON32_PROVIDER_WINNT50 As Long = 3
' Influenced from the example at http://aspalliance.com/39
Public Shared Function Login(ByVal uid As String, ByVal pwd As String) As Boolean
' Get the user's domain name.
Dim domainName As String = My.User.Name.Substring(0, My.User.Name.IndexOf("\"))
' This token is returned by the LogonUser API call (variable is passed ByRef).
Dim token As IntPtr
If LogonUser(uid, domainName, pwd, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, token) Then
' Added this line per response to this question:
WindowsIdentity.Impersonate(token)
' If the login succeeds, then impersonate that user by changing CurrentPrincipal.
Dim wi As New Principal.WindowsIdentity(token)
Dim wp As New Principal.WindowsPrincipal(wi)
My.User.CurrentPrincipal = wp
Return True
Else
Return False
End If
End Function
但是,应用程序使用的.dll具有连接到SQL Server 2000的数据访问层。在连接字符串中使用“integrated security=sspi”的SQL Server似乎正在接收登录到Windows的帐户的登录信息,而不是在WinForms应用程序代码和.dll应用程序代码中单步执行代码时返回my.user.currentprincipal.identity的帐户。
WinForms应用程序和.dll代码都正确地将my.user.currentprincipal.identity识别为登录到应用程序的帐户,而不是Windows。它只是不传播到SQL Server。在T-SQL中,存储过程将suser_sname()写入表的列可以证明这一点。
有人知道我怎么了吗?
编辑:
我加了一行
WindowsIdentity.Impersonate(token)
如前所述,但现在当我的.dll尝试创建SQL Server连接时,它会引发此错误:
用户“nt authority\anonymous logon”登录失败。