简体   繁体   English

VBA:使用Windows身份验证登录

[英]VBA: Login using Windows Authentication

I have a an Access App that requires the user to enter their Windows domain user and password to enter. 我有一个Access App,要求用户输入其Windows域用户和密码才能输入。 I have used the following VBA code to accomplish this: 我已使用以下VBA代码完成此操作:

Function WindowsLogin(ByVal strUserName As String, ByVal strpassword As String, ByVal strDomain As String) As Boolean
    'Authenticates user and password entered with Active Directory. 

    On Error GoTo IncorrectPassword

    Dim oADsObject, oADsNamespace As Object
    Dim strADsPath As String

    strADsPath = "WinNT://" & strDomain
    Set oADsObject = GetObject(strADsPath)
    Set oADsNamespace = GetObject("WinNT:")
    Set oADsObject = oADsNamespace.OpenDSObject(strADsPath, strDomain & "\" & strUserName, strpassword, 0)

    WindowsLogin = True    'ACCESS GRANTED

ExitSub:
    Exit Function

IncorrectPassword:
    WindowsLogin = False   'ACCESS DENIED
    Resume ExitSub
End Function

I notice that sometimes when the information is entered correctly, access is denied. 我注意到有时正确输入信息会拒绝访问。 I tried to debug once and it gave the error: "The network path was not found. " on the Set oADsObject = oADsNamespace.OpenDSObject) line. 我尝试调试一次,但在Set oADsObject = oADsNamespace.OpenDSObject)行上给出了错误:“找不到网络路径。”

Not sure why this occurs sometimes. 不知道为什么有时会发生这种情况。 Is it better to convert to LDAP instead? 改为转换为LDAP更好吗? I have tried but can't construct the LDAP URL correctly. 我已经尝试过,但无法正确构造LDAP URL。

If the user is already authenticated via their Windows login, why make them enter the details again? 如果用户已经通过其Windows登录名进行了身份验证,为什么还要让他们再次输入详细信息?

If you need to know which user is logged in, you can get the username very easily by the following function: 如果您需要知道哪个用户登录,可以通过以下功能很容易地获得用户名:

Declare Function IGetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal sBuffer As String, lSize As Long) As Long

Function GetUserName() As String

    On Error Resume Next

    Dim sBuffer As String
    Dim lSize As Long
    Dim x As Long

    sBuffer = Space$(32)
    lSize = Len(sBuffer)
    x = IGetUserName(sBuffer, lSize)
    GetUserName = left$(sBuffer, lSize - 1)

End Function

In GxP environment it is additionally needed to enter at least password. 在GxP环境中,还需要至少输入密码。 It doesn't matter if You are logged to Windows, You need to confirm it again. 您是否登录Windows都没有关系,您需要再次确认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM