VBA:使用 Windows 身份验证登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12144282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA: Login using Windows Authentication
提问by Rick
I have a an Access App that requires the user to enter their Windows domain user and password to enter. I have used the following VBA code to accomplish this:
我有一个 Access 应用程序,它要求用户输入他们的 Windows 域用户名和密码才能进入。我使用以下 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? I have tried but can't construct the LDAP URL correctly.
不知道为什么有时会发生这种情况。改为转换为 LDAP 是否更好?我已尝试但无法正确构建 LDAP URL。
回答by Max Vernon
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
回答by Piotr
In GxP environment it is additionally needed to enter at least password. It doesn't matter if You are logged to Windows, You need to confirm it again.
在 GxP 环境中,至少还需要输入密码。如果您登录到 Windows 没有关系,您需要再次确认。