【发布时间】:2017-10-09 07:54:46
【问题描述】:
我想知道用户是否为其 Active Directory 用户输入了正确的域、用户和密码组合。
我尝试制作一个无法连接的非常简单的程序,但通过阅读错误消息我可以知道用户/密码是否正确。
这是基于技巧的(逻辑是读取异常消息),无论如何我在 2 台服务器上测试了这个原型,我注意到异常消息在服务器之间发生变化,所以这是不可靠的。
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;
如果消息包含“服务器”,我设置“已连接”的原因是我的 本地机器(实际上在我公司的 ldap 服务器上)以防万一(域、用户和密码)服务器回复“服务器需要更安全的身份验证”,因此“服务器”一词在那里,而在其他情况下它说“错误的用户或密码”。因为这必须在意大利语和英语服务器上工作,所以我将“服务器”和“密码”设置为可靠的词。无论如何,我在另一台给出不同错误的服务器上进行了测试。
我从回复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;
【问题讨论】:
标签: delphi ldap delphi-10-seattle