VB.NET 2008 WinForms アプリケーションでユーザーを「偽装」して、実際に Windows にログインしているユーザーに関係なく、アプリケーションが PC 上の任意のユーザーの Active Directory ログインを受け入れることができるようにする必要があります。アプリケーションの 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
ただし、アプリケーションは、SQL Server 2000 に接続しているデータ アクセス レイヤーで .DLL を使用します。SQL Server は、接続文字列で「Integrated Security=SSPI」を使用して、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' のログインに失敗しました。