Hyperf方案 LDAP/AD 企业登录集成
用 directorytree/ldaprecord 最好下面完整实现tive Directory2025)---核心思路 · ↓196tokens)用户输入账号密码 ↓ 去公司 AD/LDAP 服务器验证不是你自己的数据库 ↓ 验证通过 → 拉取用户信息姓名、邮箱、部门、角色组 ↓ 生成 JWT Token 返回给前端 ↓ 后续请求带 Token正常鉴权---安装 composer require directorytree/ldaprecord hyperf/jwt-auth---目录结构 app/Controller/AuthController.php # 登录接口 Service/LdapService.php # LDAP核心逻辑 Middleware/JwtMiddleware.php # Token验证 config/autoload/ldap.php # LDAP配置---1.配置// config/autoload/ldap.phpreturn[default[hosts[env(LDAP_HOST,192.168.1.10)],portenv(LDAP_PORT,389),base_dnenv(LDAP_BASE_DN,DCcompany,DCcom),// 用一个只读服务账号去查询不能用普通用户usernameenv(LDAP_USERNAME,CNldap-reader,OUServiceAccounts,DCcompany,DCcom),passwordenv(LDAP_PASSWORD,service-account-password),use_sslenv(LDAP_SSL,false),// 生产环境建议开启 LDAPSuse_tlsenv(LDAP_TLS,false),],];LDAP_HOST192.168.1.10LDAP_BASE_DNDCcompany,DCcom LDAP_USERNAMECNldap-reader,OUServiceAccounts,DCcompany,DCcom LDAP_PASSWORDyour-service-password---2.LDAP 服务核心// app/Service/LdapService.php?php namespace App\Service;use LdapRecord\Connection;use LdapRecord\Auth\BindException;classLdapService{private Connection $conn;private array $config;publicfunction__construct(){$this-configconfig(ldap.default);$this-connnewConnection($this-config);$this-conn-connect();}/** * 登录验证 * 流程先用服务账号查到用户的完整DN再用用户自己的密码去绑定验证 */publicfunctionlogin(string $username,string $password):?array{// 第一步用服务账号查找这个用户因为直接绑定需要完整DN用户不知道自己的DN$user$this-findUser($username);if(!$user){returnnull;// 用户不存在}// 第二步用用户自己的密码验证绑定到LDAPtry{$this-conn-auth()-attempt($user[dn],$password,$bindAsUsertrue);}catch(BindException){returnnull;// 密码错误}return$user;}/** * 查找用户返回用户信息 */publicfunctionfindUser(string $username):?array{// sAMAccountName 是 AD 里的登录名就是你平时登录Windows用的那个$result$this-conn-query()-where(sAMAccountName,,$username)-whereEnabled()// 只查启用的账号-first();if(!$result){returnnull;}return[dn$result[dn],username$this-attr($result,samaccountname),name$this-attr($result,displayname)?:$this-attr($result,cn),email$this-attr($result,mail),department$this-attr($result,department),title$this-attr($result,title),// 职位phone$this-attr($result,telephonenumber),groups$this-getUserGroups($result),// 所属AD组];}/** * 获取用户所属的AD安全组用来做权限控制 */privatefunctiongetUserGroups(array $entry):array{if(empty($entry[memberof])){return[];}$groupsis_array($entry[memberof])?$entry[memberof]:[$entry[memberof]];// 从 CNIT部门,OUGroups,DCcompany,DCcom 里提取 IT部门returnarray_map(function($dn){preg_match(/^CN([^,])/i,$dn,$matches);return$matches[1]??$dn;},$groups);}// LDAP返回的属性值是数组取第一个privatefunctionattr(array $entry,string $key):string{$val$entry[$key]??;returnis_array($val)?($val[0]??):$val;}}---3.登录控制器// app/Controller/AuthController.php?php namespace App\Controller;use App\Service\LdapService;use Hyperf\Di\Annotation\Inject;use Hyperf\HttpServer\Annotation\Controller;use Hyperf\HttpServer\Annotation\PostMapping;use Hyperf\HttpServer\Contract\RequestInterface;use Hyperf\HttpServer\Contract\ResponseInterface;use Phper666\JWTAuth\JWT;#[Controller(prefix:/auth)]classAuthController{#[Inject]private LdapService $ldap;#[Inject]private JWT $jwt;#[PostMapping(path:/login)]publicfunctionlogin(RequestInterface $request,ResponseInterface $response){$username$request-input(username);$password$request-input(password);if(!$username||!$password){return$response-json([code400,msg账号密码不能为空]);}$user$this-ldap-login($username,$password);if(!$user){return$response-json([code401,msg账号或密码错误]);}// 生成 JWT把用户信息存进去$token$this-jwt-getToken(default,[username$user[username],name$user[name],email$user[email],department$user[department],groups$user[groups],]);return$response-json([code200,msg登录成功,data[token$token-toString(),userinfo$user,],]);}#[PostMapping(path:/logout)]publicfunctionlogout(ResponseInterface $response){$this-jwt-logout();return$response-json([code200,msg已退出]);}}---4.权限中间件按AD组控制权限// app/Middleware/LdapGroupMiddleware.php?php namespace App\Middleware;use Phper666\JWTAuth\JWT;use Psr\Http\Message\ResponseInterface;use Psr\Http\Message\ServerRequestInterface;use Psr\Http\Server\MiddlewareInterface;use Psr\Http\Server\RequestHandlerInterface;classLdapGroupMiddlewareimplementsMiddlewareInterface{publicfunction__construct(private JWT $jwt){}publicfunctionprocess(ServerRequestInterface $request,RequestHandlerInterface $handler):ResponseInterface{$payload$this-jwt-getParserData();$groups$payload[groups]??[];// 把用户的AD组信息注入请求后续控制器可以直接用$request$request-withAttribute(user,$payload)-withAttribute(groups,$groups);return$handler-handle($request);}}// 在控制器里检查权限publicfunctionadminAction(RequestInterface $request){$groups$request-getAttribute(groups,[]);if(!in_array(IT管理员,$groups)){return[code403,msg无权限];}// 业务逻辑...}---5.路由配置// config/routes.phpRouter::post(/auth/login,[AuthController::class,login]);// 需要登录的接口加 JWT 中间件Router::addGroup(/api,function(){Router::get(/profile,[UserController::class,profile]);Router::get(/admin,[AdminController::class,index]);},[middleware[\Phper666\JWTAuth\Middleware\JWTAuthMiddleware::class,LdapGroupMiddleware::class]]);---整体流程图 前端 POST/auth/login{username,password}↓ LdapService::login()↓ 用服务账号 查 AD 找到用户DN ──→ 用户不存在 → 返回401↓ 找到了 用用户密码绑定验证 ──→ 密码错误 → 返回401↓ 验证通过 拉取姓名/邮箱/部门/AD组 ↓ 生成JWT Token ↓ 返回Token给前端 后续请求带Token → 中间件解析 → 注入用户信息 → 控制器按AD组判断权限---常见 AD 属性对照 ┌─────────────────┬───────────────────────┐ │ 属性 │ 含义 │ ├─────────────────┼───────────────────────┤ │ sAMAccountName │ 登录名如 zhangsan │ ├─────────────────┼───────────────────────┤ │ displayName │ 显示名如 张三 │ ├─────────────────┼───────────────────────┤ │ mail │ 邮箱 │ ├─────────────────┼───────────────────────┤ │ department │ 部门 │ ├─────────────────┼───────────────────────┤ │ title │ 职位 │ ├─────────────────┼───────────────────────┤ │ memberOf │ 所属安全组 │ ├─────────────────┼───────────────────────┤ │ telephoneNumber │ 电话 │ └─────────────────┴───────────────────────┘ 生产环境记得开 use_ssltrue用 LDAPS端口636明文传密码不安全。