且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Active Directory 对 Intranet 站点上的用户进行身份验证

更新时间:2023-12-01 13:24:22

如果您只寻找身份验证而不是其他任何东西,那么您可能只需要几行代码.

If you are looking only for authentication and nothing else, you may get away with only a few lines of code.

首先,确保您的 php 中ldap 已启用.

First, ensure you have ldap enabled in your php.

这里是纯 php 实现:
(请注意,这样做时,您应该确保您确实拥有来自用户的用户名和密码 - 对于 AD,匿名绑定几乎总是返回 true)

Here's pure php implementation:
(note that when doing it this way you should ensure that you DO HAVE a username and a password from a user - anonymous binding will almost always return true for AD)

$link = ldap_connect('domain.com'); // Your domain or domain server

if(! $link) {
    // Could not connect to server - handle error appropriately
}

ldap_set_option($link, LDAP_OPT_PROTOCOL_VERSION, 3); // Recommended for AD

// Now try to authenticate with credentials provided by user
if (! ldap_bind($link, 'username@domain.com', 'SomeSecret')) {
    // Invalid credentials! Handle error appropriately
}
// Bind was successful - continue

如果您希望使用 Active Directory 做更多有趣的事情,例如提取有关当前登录用户的一些信息,我强烈建议您使用框架来为您完成繁重的工作.如前所述,adLDAP 是一个不错的选择,如果您运行 PHP 5.4,我敢于推荐 AD-X 我积极开发的库(您可以通过 Composer 安装).

If you expect to do more fun stuff with Active Directory like pulling some information about currently logged in user I strongly recommend using a framework to do the heavy lifting for you. As already mentioned, adLDAP is a good one and if you run PHP 5.4 I dare recommending the AD-X library which I actively develop (you can install it via Composer).

借助 AD-X 库,您可以使用以下代码验证用户的凭据:

With the AD-X library, you can verify a user's credentials using this code:

try {
    $link = new ADXCoreLink('domain.com'); // Establish connection to AD
    $link->bind('username@domain.com', 'SomeSecret'); // Authenticate user
}
catch (ADXCoreServerUnreachableException $e) {
    // Unable to connect to server, handle error
}
catch (ADXCoreInvalidCredentialsException $e) {
    // Invalid credentials supplied
}
catch (Exception $e) {
    // Something else happened, check the exception and handle appropriately
}

// Successfully authenticated if no exception has been thrown

随意选择最适合您的.但是,如果您希望做的不仅仅是身份验证,我强烈建议您使用一个库来处理 ldap 工作 - 当事情不像您期望的那样工作时,它会为您节省大量时间并可能会感到沮丧.

Feel free to choose which suits you best. However, if you expect to do more than authenticate I strongly suggest you use a library for the ldap work - it will save you a lot of time and possibly frustration when things do not work as you would expect them to.

此外,如果您不确定您可以/应该使用哪些信息来连接和进行身份验证,请随时查看我的 关于此主题的先前答案.

Also, if in doubt what information you can/should use to connect and to authenticate feel free to check my previous answer on this topic.