身份验证组件

您可以使用 AuthenticationComponent 访问身份验证的结果,获取用户身份和注销用户。在您的 AppController::initialize() 中加载组件,就像任何其他组件一样

$this->loadComponent('Authentication.Authentication', [
    'logoutRedirect' => '/users/login'  // Default is false
]);

加载后,AuthenticationComponent 将要求所有操作都具有经过身份验证的用户,但不会执行其他访问控制检查。您可以使用 allowUnauthenticated() 禁用针对特定操作的此检查

// In your controller's beforeFilter method.
$this->Authentication->allowUnauthenticated(['view']);

访问已登录用户

您可以使用身份验证组件获取经过身份验证的用户的身份数据

$user = $this->Authentication->getIdentity();

您也可以直接从请求实例中获取身份

$user = $request->getAttribute('identity');

检查登录状态

您可以通过访问结果对象来检查身份验证过程是否成功

// Using Authentication component
$result = $this->Authentication->getResult();

// Using request object
$result = $request->getAttribute('authentication')->getResult();

if ($result->isValid()) {
    $user = $request->getAttribute('identity');
} else {
    $this->log($result->getStatus());
    $this->log($result->getErrors());
}

getStatus() 返回的结果集对象状态将与结果对象中的以下常量之一匹配

  • ResultInterface::SUCCESS,成功时。

  • ResultInterface::FAILURE_IDENTITY_NOT_FOUND,无法找到身份时。

  • ResultInterface::FAILURE_CREDENTIALS_INVALID,凭据无效时。

  • ResultInterface::FAILURE_CREDENTIALS_MISSING,请求中缺少凭据时。

  • ResultInterface::FAILURE_OTHER,发生任何其他类型的错误时。

getErrors() 返回的错误数组包含来自进行身份验证尝试的特定系统(例如 LDAP 或 OAuth)的附加信息。例如,LDAP 或 OAuth 会在此处放置特定于其实现的错误,以便于记录和调试原因。但是,大多数包含的验证器不会在此处放置任何内容。

注销身份

要注销身份,只需执行以下操作

$this->Authentication->logout();

如果您已设置 logoutRedirect 配置,则 Authentication::logout() 将返回该值,否则将返回 false。在任何情况下,它都不会执行任何实际重定向。

或者,除了组件之外,您也可以使用服务注销

$return = $request->getAttribute('authentication')->clearIdentity($request, $response);

返回的结果将包含如下数组

[
    'response' => object(Cake\Http\Response) { ... },
    'request' => object(Cake\Http\ServerRequest) { ... },
]

注意

这将返回一个包含请求和响应对象的数组。由于两者都是不可变的,因此您将获得新的对象。根据您正在使用的上下文,如果您想继续使用已修改的响应和请求对象,您将必须从现在开始使用这些实例。

配置自动身份验证检查

默认情况下,AuthenticationComponent 会在 Controller.startup 事件期间自动强制使用身份。您可以改为在 Controller.initialize 事件期间应用此检查

// In your controller's initialize() method.
$this->loadComponent('Authentication.Authentication', [
    'identityCheckEvent' => 'Controller.initialize',
]);

您也可以使用 requireIdentity 选项完全禁用身份检查。