中间件

AuthenticationMiddleware 是身份验证插件的核心。它会拦截每个请求,并尝试使用其中一个验证器来验证用户。每个验证器都会按顺序进行尝试,直到用户被验证或未找到用户。authenticationidentityauthenticationResult 属性会设置在请求中,包含找到的身份和身份验证结果对象,该对象可能包含验证器提供的其他错误。

在每个请求结束时,identity 会被持久保存到每个有状态验证器中,比如 Session 验证器。

配置

中间件的所有配置都在 AuthenticationService 上进行。在服务中,可以使用以下配置选项

  • identityClass - 身份类的名称或可调用的身份构建器。

  • identityAttribute - 用于存储身份的请求属性。默认值为 identity

  • unauthenticatedRedirect - 重定向未经身份验证的错误的 URL。

  • queryParam - 包含先前被阻止的 URL 的查询字符串参数的名称,或者为 null 以禁用附加被拒绝的 URL。默认值为 null

配置多个身份验证设置

如果您的应用程序需要针对应用程序的不同部分使用不同的身份验证设置,例如 API 和 Web UI。您可以通过在应用程序的 getAuthenticationService() 钩子方法中使用条件逻辑来实现。通过检查请求对象,您可以适当地配置身份验证

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
    $path = $request->getPath();

    $service = new AuthenticationService();
    if (strpos($path, '/api') === 0) {
        // Accept API tokens only
        $service->loadAuthenticator('Authentication.Token');
        $service->loadIdentifier('Authentication.Token');

        return $service;
    }

    // Web authentication
    // Support sessions and form login.
    $service->loadAuthenticator('Authentication.Session');
    $service->loadAuthenticator('Authentication.Form');

    $service->loadIdentifier('Authentication.Password');

    return $service;
}

虽然上面的例子使用的是路径前缀,但您也可以将类似的逻辑应用于子域、域或请求中存在的任何其他标头或属性。