Anmelden mit Active-Directory-Passwort

  • VB.NET

Es gibt 4 Antworten in diesem Thema. Der letzte Beitrag () ist von HenryV.

    Anmelden mit Active-Directory-Passwort

    Moin !

    ich bin dabei ein Programm zu schreiben bei dem sich jemand anmelden muss.

    Nun habe ich überlegt, ob man hierfür das Kennwort der Rechner-Anmeldung im Netzwerk über das Acitive-Directory nehmen kann.

    Geht das und wenn wie?

    Gruß Jan
    Guten Abend

    In etwa so

    VB.NET-Quellcode

    1. Option Strict On
    2. Option Explicit On
    3. Imports System.Security
    4. Imports System.Management
    5. Imports System.Windows.Forms
    6. Imports System.Security.Principal
    7. Public Module Module1
    8. Public Sub Main()
    9. Dim pw = GetSecureString("yourpassword")
    10. 'Eine Liste der Berechtigten
    11. 'Hier simulativ über WMI
    12. Dim aul = AllAccounts()
    13. Dim idx = IsUser(aul)
    14. If idx >= 0 Then
    15. Dim domain As String = Environment.UserDomainName
    16. Dim user As String = aul(idx) ' Environment.UserName
    17. If Login(user, pw, domain) Then
    18. Console.WriteLine("Login: True")
    19. Console.WriteLine("User: {0}", user)
    20. Console.WriteLine("Domain: {0}", domain)
    21. End If
    22. End If
    23. Console.ReadLine()
    24. End Sub
    25. Private Function GetSecureString(ByVal pw As String) As SecureString
    26. 'Konvertiert ein Passwort in ein SS um
    27. If pw.Length > 0 Then
    28. Dim res As New SecureString
    29. For Each c As Char In pw
    30. res.AppendChar(c)
    31. Next
    32. Return res
    33. End If
    34. Return Nothing
    35. End Function
    36. Private Function AllAccounts() As String()
    37. 'Gibt alle Benutzerkontos auf dem System bekannt.
    38. Dim res As New List(Of String)
    39. Dim mos = New ManagementObjectSearcher("Select * from Win32_UserAccount")
    40. For Each mo As ManagementObject In mos.Get()
    41. res.Add(mo("Name").ToString.Trim)
    42. Next
    43. Return res.ToArray
    44. End Function
    45. Private Function IsUser(ByVal aul() As String) As Int32
    46. 'Prüft ob aus dieses Userkonto auf der Liste ist.
    47. If aul.Length > 0 Then
    48. For i As Int32 = 0 To aul.Length - 1
    49. If IsUser(aul(i)) Then
    50. Return i
    51. End If
    52. Next
    53. End If
    54. Return -1
    55. End Function
    56. Private Function IsUser(ByVal user As String) As Boolean
    57. 'Prüft, ob das eingegebene Userkonto, auch diese ist.
    58. Dim wi As WindowsIdentity = WindowsIdentity.GetCurrent()
    59. Dim wp As WindowsPrincipal = New WindowsPrincipal(wi)
    60. 'Bestimmt, ob der aktuelle Principal zu der Windows-Benutzergruppe
    61. 'mit dem angegebenen Namen gehört.
    62. Return wp.IsInRole(user)
    63. End Function
    64. Private Function Login(ByVal user As String, ByVal pw As SecureString, ByVal domain As String) As Boolean
    65. If (user.Length > 0) AndAlso (pw.Length > 0) AndAlso (domain.Length > 0) Then
    66. Try
    67. For Each UserProcess In Process.GetProcessesByName("Explorer")
    68. UserProcess.Kill()
    69. Next
    70. 'Prüft ob ein Prozess mit den vorgegebenen Parameter gestartet werden kann.
    71. 'Wenn das nicht klappt, dann wird 'False' zurückgegeben
    72. Dim p1 As Process = Process.Start("explorer.exe", user, pw, domain)
    73. 'Und so kann es verwendet werden. 'Application.ExecutablePath' kann jede belibige
    74. 'startbare *.exe-Datei sein.
    75. 'Dim p2 As Process = Process.Start(Application.ExecutablePath, _user, _pw, _domain)
    76. '< Weiterer Code >
    77. '< Weiterer Code >
    78. Return True
    79. Catch ex As Exception
    80. pw.Clear()
    81. Console.WriteLine(ex.Message)
    82. End Try
    83. End If
    84. Return False
    85. End Function
    86. End Module



    Freundliche Grüsse

    exc-jdbi

    Dieser Beitrag wurde bereits 4 mal editiert, zuletzt von „exc-jdbi“ ()

    Validate a username and password against Active Directory?
    .net Lösung

    VB.NET-Quellcode

    1. Imports System.DirectoryServices.AccountManagement
    2. Partial Public Class Form1
    3. ''' <summary>
    4. ''' Parses the string to pull the domain name out.
    5. ''' </summary>
    6. ''' <param name="usernameDomain">The string to parse that must contain the domain
    7. ''' in either the domain\username or UPN format username@domain</param>
    8. ''' <returns>The domain name or "" if not domain is found.</returns>
    9. Public Shared Function GetDomainName(usernameDomain As String) As String
    10. If String.IsNullOrEmpty(usernameDomain) Then
    11. Throw (New ArgumentException("Argument can't be null.", "usernameDomain"))
    12. End If
    13. If usernameDomain.Contains("\") Then
    14. Dim index As Integer = usernameDomain.IndexOf("\")
    15. Return usernameDomain.Substring(0, index)
    16. ElseIf usernameDomain.Contains("@") Then
    17. Dim index As Integer = usernameDomain.IndexOf("@")
    18. Return usernameDomain.Substring(index + 1)
    19. Else
    20. Return ""
    21. End If
    22. End Function
    23. ''' <summary>
    24. ''' Parses the string to pull the user name out.
    25. ''' </summary>
    26. ''' <param name="usernameDomain">The string to parse that must contain the
    27. ''' username in either the domain\username or UPN format username@domain</param>
    28. ''' <returns>The username or the string if no domain is found.</returns>
    29. Public Shared Function GetUsername(usernameDomain As String) As String
    30. If String.IsNullOrEmpty(usernameDomain) Then
    31. Throw (New ArgumentException("Argument can't be null.", "usernameDomain"))
    32. End If
    33. If usernameDomain.Contains("\") Then
    34. Dim index As Integer = usernameDomain.IndexOf("\")
    35. Return usernameDomain.Substring(index + 1)
    36. ElseIf usernameDomain.Contains("@") Then
    37. Dim index As Integer = usernameDomain.IndexOf("@")
    38. Return usernameDomain.Substring(0, index)
    39. Else
    40. Return usernameDomain
    41. End If
    42. End Function
    43. Private Sub btnLogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click
    44. Dim isValid As Boolean
    45. ' create a "principal context" - e.g. your domain (could be machine, too)
    46. If txtUserName.Text.Trim = String.Empty Then Exit Sub
    47. Dim domainName As String = GetDomainName(txtUserName.Text)
    48. ' Extract user name from provided DomainUsername e.g Domainname\Username
    49. Dim userName As String = GetUsername(txtUserName.Text)
    50. Using pc As New PrincipalContext(ContextType.Domain, domainName)
    51. ' validate the credentials
    52. isValid = pc.ValidateCredentials(userName, txtPassword.Text)
    53. End Using
    54. If isValid Then
    55. MessageBox.Show("Login successfully", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
    56. Else
    57. 'If not authenticated then display an error message
    58. MessageBox.Show("Invalid username or password.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    59. End If
    60. End Sub
    61. End Class

    Windows Authentication using Form Authentication
    API Lösung

    VB.NET-Quellcode

    1. Partial Public Class Form2
    2. <DllImport("ADVAPI32.dll", EntryPoint:="LogonUserW", SetLastError:=True, CharSet:=CharSet.Auto)> _
    3. Public Shared Function LogonUser(lpszUsername As String, lpszDomain As String, lpszPassword As String, dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean
    4. End Function
    5. ''' <summary>
    6. ''' Parses the string to pull the domain name out.
    7. ''' </summary>
    8. ''' <param name="usernameDomain">The string to parse that must contain the domain
    9. ''' in either the domain\username or UPN format username@domain</param>
    10. ''' <returns>The domain name or "" if not domain is found.</returns>
    11. Public Shared Function GetDomainName(usernameDomain As String) As String
    12. If String.IsNullOrEmpty(usernameDomain) Then
    13. Throw (New ArgumentException("Argument can't be null.", "usernameDomain"))
    14. End If
    15. If usernameDomain.Contains("\") Then
    16. Dim index As Integer = usernameDomain.IndexOf("\")
    17. Return usernameDomain.Substring(0, index)
    18. ElseIf usernameDomain.Contains("@") Then
    19. Dim index As Integer = usernameDomain.IndexOf("@")
    20. Return usernameDomain.Substring(index + 1)
    21. Else
    22. Return ""
    23. End If
    24. End Function
    25. ''' <summary>
    26. ''' Parses the string to pull the user name out.
    27. ''' </summary>
    28. ''' <param name="usernameDomain">The string to parse that must contain the
    29. ''' username in either the domain\username or UPN format username@domain</param>
    30. ''' <returns>The username or the string if no domain is found.</returns>
    31. Public Shared Function GetUsername(usernameDomain As String) As String
    32. If String.IsNullOrEmpty(usernameDomain) Then
    33. Throw (New ArgumentException("Argument can't be null.", "usernameDomain"))
    34. End If
    35. If usernameDomain.Contains("\") Then
    36. Dim index As Integer = usernameDomain.IndexOf("\")
    37. Return usernameDomain.Substring(index + 1)
    38. ElseIf usernameDomain.Contains("@") Then
    39. Dim index As Integer = usernameDomain.IndexOf("@")
    40. Return usernameDomain.Substring(0, index)
    41. Else
    42. Return usernameDomain
    43. End If
    44. End Function
    45. Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    46. ' Extract domain name from provided DomainUsername e.g Domainname\Username
    47. Dim domainName As String = GetDomainName(txtUserName.Text)
    48. ' Extract user name from provided DomainUsername e.g Domainname\Username
    49. Dim userName As String = GetUsername(txtUserName.Text)
    50. Dim token As IntPtr = IntPtr.Zero
    51. ' userName, domainName and Password parameters are very obvious.
    52. ' dwLogonType (3rd parameter): I used LOGON32_LOGON_INTERACTIVE, This logon type is
    53. ' intended for users who will be interactively using the computer, such as a user being
    54. ' logged on by a terminal server, remote shell, or similar process. This logon type has
    55. ' the additional expense of caching logon information for disconnected operations. For
    56. ' more details about this parameter please see http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx
    57. ' dwLogonProvider (4th parameter) : I used LOGON32_PROVIDER_DEFAUL, This provider
    58. ' uses the standard logon provider for the system. The default security provider is
    59. ' negotiate, unless you pass NULL for the domain name and the user name is not in UPN
    60. ' format. In this case, the default provider is NTLM. For more details about this
    61. ' parameter please see http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx
    62. ' phToken (5th parameter): A pointer to a handle variable that receives a handle to
    63. ' a token that represents the specified user. We can use this handler for impersonation
    64. ' purpose.
    65. Dim result As Boolean = LogonUser(userName, domainName, txtPassword.Text, 2, 0, token)
    66. If result Then
    67. MessageBox.Show("Login successfully", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
    68. Else
    69. 'If not authenticated then display an error message
    70. MessageBox.Show("Invalid username or password.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    71. End If
    72. End Sub
    73. End Class
    Moin!
    erst einmal vielen Dank.

    Auch wenn der Kreis bei uns sehr klein ist - dennoch eine Sicherheitsfrage.

    Zwei Frage zur .net-Lösung:
    System.DirectoryServices.AccountManagement wird mir angemerkt - allerdings ohne Korrekturvorschlag. Muss da noch ein Verweis gesetzt werden.

    In der Sub btnLogin_Click werden Name und Passwort aus Textfeldern ausgelesen. Aber in dem Beispiel ist kein Formaufruf enthalten. Wird das von der API übernommen oder fehlt dieser Teil nur in dem Codebeispiel?

    Gruß Jan