I am trying to authenticate using the Windows Credential dialog and I have this code:
Code:
Imports System.Runtime.InteropServices
Imports System.Text
Namespace Domain
Module WindowsSecurityCredentials
<DllImport("credui.dll", CharSet:=CharSet.Unicode)>
Private Function CredUIPromptForWindowsCredentialsW(
ByRef pUiInfo As CREDUI_INFO,
dwAuthError As Integer,
ByRef pulAuthPackage As UInteger,
pvInAuthBuffer As IntPtr,
ulInAuthBufferSize As UInteger,
ByRef ppvOutAuthBuffer As IntPtr,
ByRef pulOutAuthBufferSize As UInteger,
ByRef pfSave As Boolean,
dwFlags As Integer
) As Integer
End Function
<DllImport("credui.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> <CLSCompliant(False)>
Private Function CredUnPackAuthenticationBuffer(
dwFlags As UInt32,
pAuthBuffer As IntPtr,
cbAuthBuffer As UInt32,
pszUserName As StringBuilder,
ByRef pcchMaxUserName As UInt32,
pszDomainName As StringBuilder,
ByRef pcchMaxDomainName As UInt32,
pszPassword As StringBuilder,
ByRef pcchMaxPassword As UInt32
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Private Structure CREDUI_INFO
Public cbSize As Integer
Public hwndParent As IntPtr
Public pszMessageText As String
Public pszCaptionText As String
Public hbmBanner As IntPtr
End Structure
Public Function AuthenticateViaCredentialDialog() As AuthenticatedUser
Dim credUI As New CREDUI_INFO With {
.cbSize = Marshal.SizeOf(GetType(CREDUI_INFO)),
.pszCaptionText = "Windows Authentication",
.pszMessageText = "Please authenticate using your Windows credentials."
}
Dim authPackage As UInteger
Dim save As Boolean = False
Dim outAuthBuffer As IntPtr = IntPtr.Zero
Dim outAuthBufferSize As UInteger
Dim result = CredUIPromptForWindowsCredentialsW(credUI, 0, authPackage, IntPtr.Zero, 0, outAuthBuffer, outAuthBufferSize, save, 0)
If (result = 0) Then
Dim username As New StringBuilder(3000)
Dim domainName As New StringBuilder(3000)
Dim password As New StringBuilder(3000)
Dim maxUserName As Integer = username.Capacity
Dim maxDomainName As Integer = domainName.Capacity
Dim maxPassword As Integer = password.Capacity
Dim unpackResult = CredUnPackAuthenticationBuffer(0, outAuthBuffer, outAuthBufferSize, username, maxUserName, domainName, maxDomainName, password, maxPassword)
Marshal.ZeroFreeGlobalAllocUnicode(outAuthBuffer)
If (unpackResult) Then
Return New AuthenticatedUser() With {
.Username = username.ToString(),
.DomainName = domainName.ToString()
}
End If
End If
Return Nothing
End Function
End Module
Public Class AuthenticatedUser
Public Property Username As String
Public Property DomainName As String
End Class
End Namespace
The problem is that while I do get something back in for my username, it appears to be encrypted. At least it starts with @@ followed by a bunch of arbitrary numbers/letters.
Is there an alternative where I can authenticate using the windows credential dialog then get the username and domain name of the person who logged in?