我需要在VB.NET 2008 WinForms应用程序中“模仿”用户,以便应用程序可以接受PC上任何用户的Active Directory登录,无论谁实际登录到Windows。我希望应用程序的My.User成为登录应用程序的人的AD帐户。我用以下代码成功完成了这个:
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.似乎SQL Server在连接字符串中使用“Integrated Security = SSPI”,正在接收已记录帐户的登录名进入Windows而不是帐户返回My.User.CurrentPrincipal.Identity,当单步执行代码时,在WinForms应用程序代码和.DLL的应用程序代码中。
WinForms应用程序和.DLL代码都正确识别My.User.CurrentPrincipal.Identity作为登录到应用程序的帐户,而不是Windows。它只是没有传播到SQL Server。这可以通过将SUSER_SNAME()写入T-SQL中的表列的存储过程来证明。
任何人都可以看到我出错的地方吗?
编辑:我已按照说明添加了行WindowsIdentity.Impersonate(token)
,但现在当我的.DLL尝试创建SQL Server连接时,它会抛出此错误:
用户'NT AUTHORITY \ ANONYMOUS LOGON'登录失败。
答案 0 :(得分:1)
您需要致电WindowsIdentity.Impersonate();
:
If LogonUser(...) Then
WindowsIdentity.Impersonate(token)