CakePHP 4:如何在中间件中获取认证信息?
解决CakePHP中间件中获取认证信息返回null的问题
问题根源
你的CompanyMiddleware存在两个核心问题:
- 未初始化
$authenticationService属性,直接调用会触发错误(当前返回null大概率是因为该属性未定义,无法正确获取认证服务) - CakePHP认证插件的认证服务实例是由
AuthenticationMiddleware附加到请求对象中的,并非通过中间件类的属性直接获取
正确实现方式
修改CompanyMiddleware的process方法,从请求对象中直接获取认证服务或已解析的身份信息:
<?php declare(strict_types=1); namespace App\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Authentication\AuthenticationServiceInterface; /** * Company middleware */ class CompanyMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { // 方式1:先获取认证服务实例,再获取身份信息 $authService = $request->getAttribute('authentication'); if ($authService instanceof AuthenticationServiceInterface) { $identity = $authService->getIdentity(); } // 方式2:直接从请求属性中获取已解析的身份信息(更简便) $identity = $request->getAttribute('identity'); dd($identity); return $handler->handle($request); } }
关键说明
AuthenticationMiddleware执行完成后,会自动将认证服务实例存入请求的authentication属性,同时将认证通过的身份信息存入identity属性- 你的中间件队列配置已经正确将
AuthenticationMiddleware放在CompanyMiddleware之前,这个顺序是合理的,确保认证逻辑优先执行 - 如果仍然返回null,请检查
Application::getAuthenticationService方法中的认证配置是否正确(比如是否定义了有效的认证器、识别器),以及用户是否已完成正常的认证流程
内容的提问来源于stack exchange,提问作者Niloy Rony
相关产品推荐
相关产品推荐

