用户认证

admin 提交于 周三, 06/07/2023 - 15:21
用户认证

认证,是系统判断访问者身份的过程,解决的是 是谁? 的问题。 鉴权,是发生在认证成功之后的,是检查已认证访问者 有什么权限? 的过程。

系统在处理一个来自浏览器的请求时, 会调用 \Drupal\Core\Authentication\AuthenticationProviderInterface 接口来检查请求是否需要认证。

/**
 * Interface for authentication providers.
 */
interface AuthenticationProviderInterface {

  /**
   * Checks whether suitable authentication credentials are on the request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return bool
   *   TRUE if authentication credentials suitable for this provider are on the
   *   request, FALSE otherwise.
   */
  public function applies(Request $request);

  /**
   * Authenticates the user.
   *
   * @param \Symfony\Component\HttpFoundation\Request|null $request
   *   The request object.
   *
   * @return \Drupal\Core\Session\AccountInterface|null
   *   AccountInterface - in case of a successful authentication.
   *   NULL - in case where authentication failed.
   */
  public function authenticate(Request $request);

}

\Drupal\Core\Authentication\AuthenticationManager 是 Drupal 系统认证逻辑所在, 系统会先调用 applies(Request $request) 方法检查请求中是否包含有支持认证的数据, 如果有则调用 authenticate(Request $request); 方法对请求进行认证, 如果认证成功,会返回一个用户账户,如果认证失败返回 Null

Drupal 支持多种认证模式,核心自带的认证模式有:

  • basic_auth 基于 http basic
  • cookie 基于 http cookie

社区模块 simple_oauth 提供了 Oauth 2.0 协议认证模式的支持。

这些认证模式都是通过实现上述接口的方式来为系统提供认证服务的, 实现了上述接口的类,并打上 authentication_provider 服务标签,认证服务就能被系统调用。 这些服务被称为 认证提供器

如果现有的认证模式不能满足开发者的要求,开发者可以自定义 认证提供器