delphi – 检查Active DIrectory中的用户身份验证
我想知道用户是否为其Active Directory用户输入了域,用户和密码的正确组合.
我尝试制作一个无法连接的非常简单的程序,但通过阅读错误消息我可以知道用户/密码是否正确. 这是基于技巧的(逻辑是在读取Exception消息),无论如何我在2台服务器上测试了这个原型,我注意到excpetion消息从服务器变为服务器,所以这是不可靠的. uses adshlp,ActiveDs_TLB; // 3 TEdit and a TButton procedure TForm4.Button1Click(Sender: TObject); Var aUser : IAdsUser; pDomain,pUser,pPassword : string; myResult : HRESULT; Counter: integer; begin pDomain := edtDomain.Text; pUser:= edtUser.Text; pPassword := edtPwd.Text; Counter := GetTickCount; Try myResult := ADsOpenObject(Format('LDAP://%s',[pDomain]),Format('%s%s',[pDomain,pUser]),pPassword,ADS_READONLY_SERVER,IAdsUser,aUser); except On E : EOleException do begin if (GetTickCount - Counter > 3000) then ShowMessage ('Problem with connection') else if Pos('password',E.Message) > 0 then ShowMessage ('wrong username or password') else if Pos('server',E.Message) > 0 then ShowMessage ('Connected') else ShowMessage('Unhandled case'); memLog.Lines.Add(E.Message); end; end end; 如果消息包含“服务器”,我设置“已连接”的原因就是我的 我从回复到this question开始做上述事情. 如何使用类似技术以更可靠的方式检查用户是否设置了正确的密码? 更新(找到解决方案) 感谢回复,我设法写这个功能,做我需要的.到目前为止看起来很可靠,我写在这里分享,希望它可以帮助别人: // This function returns True if the provided parameters are correct // login credentials for a user in the specified Domain // From empirical tests it seems reliable function UserCanLogin(aDomain,aUser,aPassword: string): Boolean; var hToken: THandle; begin Result := False; if (LogonUser(pChar(aUser),pChar(aDomain),pChar(aPassword),LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,hToken)) then begin CloseHandle(hToken); Result := True; end; end; 解决方法
您可以使用LogonUser功能验证用户登录,例如: if (LogonUser(pChar(_Username),pChar(_ADServer),pChar(_Password),hToken)) then begin CloseHandle(hToken); //... //DoSomething end else raise Exception.Create(SysErrorMessage(GetLastError)); 注意:您必须在域计算机中使用LogonUser才能使用域登录,否则该函数将始终返回用户名或密码不正确 替代方案是使用TLDAPSend,例如: function _IsAuthenticated(const lpszUsername,lpszDomain,lpszPassword: string): Boolean; var LDAP : TLDAPSend; begin Result := False; if ( (Length(lpszUsername) = 0) or (Length(lpszPassword) = 0) )then Exit; LDAP := TLDAPSend.Create; try LDAP.TargetHost := lpszDomain; LDAP.TargetPort := '389'; .... LDAP.UserName := lpszUsername + #64 + lpszDomain;; LDAP.Password := lpszPassword; Result := LDAP.Login; finally LDAP.Free; end; end;
尝试使用FormatMessage function FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM,nil,myResult,LANG_ENGLISH or SUBLANG_ENGLISH_US,lpMsg,nil); MessageBox(0,'Msg',0); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |