ASCII码 ASCII码

基于Laravel Auth自定义接口API用户认证的实现方法

发布于:2022-05-04 15:51:43  栏目:技术文档

这篇文章主要给大家介绍了基于Laravel Auth自定义接口API用户认证的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

基于 laravel 默认的 auth 实现 api 认证现在微服务越来越流行了. 很多东西都拆分成独立的系统,各个系统之间没有直接的关系. 这样我们如果做用户认证肯定是统一的做一个独立的 用户认证 系统,而不是每个业务系统都要重新去写一遍用户认证相关的东西. 但是又遇到一个问题了. laravel 默认的auth 认证 是基于数据库做的,如果要微服务架构可怎么做呢?实现代码如下:UserProvider 接口:

  1. // 通过唯一标示符获取认证模型
  2. public function retrieveById($identifier);
  3. // 通过唯一标示符和 remember token 获取模型
  4. public function retrieveByToken($identifier, $token);
  5. // 通过给定的认证模型更新 remember token
  6. public function updateRememberToken(Authenticatable $user, $token);
  7. // 通过给定的凭证获取用户,比如 email 或用户名等等
  8. public function retrieveByCredentials(array $credentials);
  9. // 认证给定的用户和给定的凭证是否符合
  10. public function validateCredentials(Authenticatable $user, array $credentials);

ravel 中默认有两个 user provider : DatabaseUserProvider & EloquentUserProvider.DatabaseUserProviderIlluminate\Auth\DatabaseUserProvider直接通过数据库表来获取认证模型.EloquentUserProviderIlluminate\Auth\EloquentUserProvider通过 eloquent 模型来获取认证模型根据上面的知识,可以知道要自定义一个认证很简单。自定义 Provider创建一个自定义的认证模型,实现 Authenticatable 接口;App\Auth\UserProvider.php

  1. <?php
  2. namespace App\Auth;
  3. use App\Models\User;
  4. use Illuminate\Contracts\Auth\Authenticatable;
  5. use Illuminate\Contracts\Auth\UserProvider as Provider;
  6. class UserProvider implements Provider
  7. {
  8. /**
  9. * Retrieve a user by their unique identifier.
  10. * @param mixed $identifier
  11. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  12. */
  13. public function retrieveById($identifier)
  14. {
  15. return app(User::class)::getUserByGuId($identifier);
  16. }
  17. /**
  18. * Retrieve a user by their unique identifier and "remember me" token.
  19. * @param mixed $identifier
  20. * @param string $token
  21. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  22. */
  23. public function retrieveByToken($identifier, $token)
  24. {
  25. return null;
  26. }
  27. /**
  28. * Update the "remember me" token for the given user in storage.
  29. * @param \Illuminate\Contracts\Auth\Authenticatable $user
  30. * @param string $token
  31. * @return bool
  32. */
  33. public function updateRememberToken(Authenticatable $user, $token)
  34. {
  35. return true;
  36. }
  37. /**
  38. * Retrieve a user by the given credentials.
  39. * @param array $credentials
  40. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  41. */
  42. public function retrieveByCredentials(array $credentials)
  43. {
  44. if ( !isset($credentials['api_token'])) {
  45. return null;
  46. }
  47. return app(User::class)::getUserByToken($credentials['api_token']);
  48. }
  49. /**
  50. * Rules a user against the given credentials.
  51. * @param \Illuminate\Contracts\Auth\Authenticatable $user
  52. * @param array $credentials
  53. * @return bool
  54. */
  55. public function validateCredentials(Authenticatable $user, array $credentials)
  56. {
  57. if ( !isset($credentials['api_token'])) {
  58. return false;
  59. }
  60. return true;
  61. }
  62. }

Authenticatable 接口:Illuminate\Contracts\Auth\AuthenticatableAuthenticatable 定义了一个可以被用来认证的模型或类需要实现的接口,也就是说,如果需要用一个自定义的类来做认证,需要实现这个接口定义的方法。

  1. <?php
  2. .
  3. .
  4. .
  5. // 获取唯一标识的,可以用来认证的字段名,比如 id,uuid
  6. public function getAuthIdentifierName();
  7. // 获取该标示符对应的值
  8. public function getAuthIdentifier();
  9. // 获取认证的密码
  10. public function getAuthPassword();
  11. // 获取remember token
  12. public function getRememberToken();
  13. // 设置 remember token
  14. public function setRememberToken($value);
  15. // 获取 remember token 对应的字段名,比如默认的 'remember_token'
  16. public function getRememberTokenName();
  17. .
  18. .
  19. .

Laravel 中定义的 Authenticatable trait,也是 Laravel auth 默认的 User 模型使用的 trait,这个 trait 定义了 User 模型默认认证标示符为 ‘id’,密码字段为password,remember token 对应的字段为 remember_token 等等。通过重写 User 模型的这些方法可以修改一些设置。实现自定义认证模型App\Models\User.php

  1. <?php
  2. namespace App\Models;
  3. use App\Exceptions\RestApiException;
  4. use App\Models\Abstracts\RestApiModel;
  5. use Illuminate\Contracts\Auth\Authenticatable;
  6. class User extends RestApiModel implements Authenticatable
  7. {
  8. protected $primaryKey = 'guid';
  9. public $incrementing = false;
  10. protected $keyType = 'string';
  11. /**
  12. * 获取唯一标识的,可以用来认证的字段名,比如 id,guid
  13. * @return string
  14. */
  15. public function getAuthIdentifierName()
  16. {
  17. return $this->primaryKey;
  18. }
  19. /**
  20. * 获取主键的值
  21. * @return mixed
  22. */
  23. public function getAuthIdentifier()
  24. {
  25. $id = $this->{$this->getAuthIdentifierName()};
  26. return $id;
  27. }
  28. public function getAuthPassword()
  29. {
  30. return '';
  31. }
  32. public function getRememberToken()
  33. {
  34. return '';
  35. }
  36. public function setRememberToken($value)
  37. {
  38. return true;
  39. }
  40. public function getRememberTokenName()
  41. {
  42. return '';
  43. }
  44. protected static function getBaseUri()
  45. {
  46. return config('api-host.user');
  47. }
  48. public static $apiMap = [
  49. 'getUserByToken' => ['method' => 'GET', 'path' => 'login/user/token'],
  50. 'getUserByGuId' => ['method' => 'GET', 'path' => 'user/guid/:guid'],
  51. ];
  52. /**
  53. * 获取用户信息 (by guid)
  54. * @param string $guid
  55. * @return User|null
  56. */
  57. public static function getUserByGuId(string $guid)
  58. {
  59. try {
  60. $response = self::getItem('getUserByGuId', [
  61. ':guid' => $guid
  62. ]);
  63. } catch (RestApiException $e) {
  64. return null;
  65. }
  66. return $response;
  67. }
  68. /**
  69. * 获取用户信息 (by token)
  70. * @param string $token
  71. * @return User|null
  72. */
  73. public static function getUserByToken(string $token)
  74. {
  75. try {
  76. $response = self::getItem('getUserByToken', [
  77. 'Authorization' => $token
  78. ]);
  79. } catch (RestApiException $e) {
  80. return null;
  81. }
  82. return $response;
  83. }
  84. }

上面 RestApiModel 是我们公司对 Guzzle 的封装,用于 php 项目各个系统之间 api 调用. 代码就不方便透漏了.Guard 接口

  1. // 判断当前用户是否登录
  2. public function check();
  3. // 判断当前用户是否是游客(未登录)
  4. public function guest();
  5. // 获取当前认证的用户
  6. public function user();
  7. // 获取当前认证用户的 id,严格来说不一定是 id,应该是上个模型中定义的唯一的字段名
  8. public function id();
  9. // 根据提供的消息认证用户
  10. public function validate(array $credentials = []);
  11. // 设置当前用户
  12. public function setUser(Authenticatable $user);

Illuminate\Contracts\Auth\GuardGuard 接口定义了某个实现了 Authenticatable (可认证的) 模型或类的认证方法以及一些常用的接口。

  1. // 判断当前用户是否登录
  2. public function check();
  3. // 判断当前用户是否是游客(未登录)
  4. public function guest();
  5. // 获取当前认证的用户
  6. ```php
  7. // 尝试根据提供的凭证验证用户是否合法
  8. public function attempt(array $credentials = [], $remember = false);
  9. // 一次性登录,不记录session or cookie
  10. public function once(array $credentials = []);
  11. // 登录用户,通常在验证成功后记录 session 和 cookie
  12. public function login(Authenticatable $user, $remember = false);
  13. // 使用用户 id 登录
  14. public function loginUsingId($id, $remember = false);
  15. // 使用用户 ID 登录,但是不记录 session 和 cookie
  16. public function onceUsingId($id);
  17. // 通过 cookie 中的 remember token 自动登录
  18. public function viaRemember();
  19. // 登出
  20. public function logout();

public function user();// 获取当前认证用户的 id,严格来说不一定是 id,应该是上个模型中定义的唯一的字段名public function id();// 根据提供的消息认证用户public function validate(array $credentials = []);// 设置当前用户public function setUser(Authenticatable $user);

  1. StatefulGuard 接口
  2. Illuminate\Contracts\Auth\StatefulGuard
  3. StatefulGuard 接口继承自 Guard 接口,除了 Guard 里面定义的一些基本接口外,还增加了更进一步、有状态的 Guard.
  4. 新添加的接口有这些:
  5. Laravel 中默认提供了 3 中 guard :RequestGuard,TokenGuard,SessionGuard.
  6. RequestGuard
  7. Illuminate\Auth\RequestGuard
  8. RequestGuard 是一个非常简单的 guard. RequestGuard 是通过传入一个闭包来认证的。可以通过调用 Auth::viaRequest 添加一个自定义的 RequestGuard.
  9. SessionGuard
  10. Illuminate\Auth\SessionGuard
  11. SessionGuard 是 Laravel web 认证默认的 guard.
  12. TokenGuard
  13. Illuminate\Auth\TokenGuard
  14. TokenGuard 适用于无状态 api 认证,通过 token 认证.
  15. 实现自定义 Guard
  16. App\Auth\UserGuard.php
  17. ```php
  18. <?php
  19. namespace App\Auth;
  20. use Illuminate\Http\Request;
  21. use Illuminate\Auth\GuardHelpers;
  22. use Illuminate\Contracts\Auth\Guard;
  23. use Illuminate\Contracts\Auth\UserProvider;
  24. class UserGuard implements Guard
  25. {
  26. use GuardHelpers;
  27. protected $user = null;
  28. protected $request;
  29. protected $provider;
  30. /**
  31. * The name of the query string item from the request containing the API token.
  32. *
  33. * @var string
  34. */
  35. protected $inputKey;
  36. /**
  37. * The name of the token "column" in persistent storage.
  38. *
  39. * @var string
  40. */
  41. protected $storageKey;
  42. /**
  43. * The user we last attempted to retrieve
  44. * @var
  45. */
  46. protected $lastAttempted;
  47. /**
  48. * UserGuard constructor.
  49. * @param UserProvider $provider
  50. * @param Request $request
  51. * @return void
  52. */
  53. public function __construct(UserProvider $provider, Request $request = null)
  54. {
  55. $this->request = $request;
  56. $this->provider = $provider;
  57. $this->inputKey = 'Authorization';
  58. $this->storageKey = 'api_token';
  59. }
  60. /**
  61. * Get the currently authenticated user.
  62. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  63. */
  64. public function user()
  65. {
  66. if(!is_null($this->user)) {
  67. return $this->user;
  68. }
  69. $user = null;
  70. $token = $this->getTokenForRequest();
  71. if(!empty($token)) {
  72. $user = $this->provider->retrieveByCredentials(
  73. [$this->storageKey => $token]
  74. );
  75. }
  76. return $this->user = $user;
  77. }
  78. /**
  79. * Rules a user's credentials.
  80. * @param array $credentials
  81. * @return bool
  82. */
  83. public function validate(array $credentials = [])
  84. {
  85. if (empty($credentials[$this->inputKey])) {
  86. return false;
  87. }
  88. $credentials = [$this->storageKey => $credentials[$this->inputKey]];
  89. $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
  90. return $this->hasValidCredentials($user, $credentials);
  91. }
  92. /**
  93. * Determine if the user matches the credentials.
  94. * @param mixed $user
  95. * @param array $credentials
  96. * @return bool
  97. */
  98. protected function hasValidCredentials($user, $credentials)
  99. {
  100. return !is_null($user) && $this->provider->validateCredentials($user, $credentials);
  101. }
  102. /**
  103. * Get the token for the current request.
  104. * @return string
  105. */
  106. public function getTokenForRequest()
  107. {
  108. $token = $this->request->header($this->inputKey);
  109. return $token;
  110. }
  111. /**
  112. * Set the current request instance.
  113. *
  114. * @param \Illuminate\Http\Request $request
  115. * @return $this
  116. */
  117. public function setRequest(Request $request)
  118. {
  119. $this->request = $request;
  120. return $this;
  121. }
  122. }

在 AppServiceProvider 的 boot 方法添加如下代码:App\Providers\AuthServiceProvider.php

  1. <?php
  2. .
  3. .
  4. .
  5. // auth:api -> token provider.
  6. Auth::provider('token', function() {
  7. return app(UserProvider::class);
  8. });
  9. // auth:api -> token guard.
  10. // @throw \Exception
  11. Auth::extend('token', function($app, $name, array $config) {
  12. if($name === 'api') {
  13. return app()->make(UserGuard::class, [
  14. 'provider' => Auth::createUserProvider($config['provider']),
  15. 'request' => $app->request,
  16. ]);
  17. }
  18. throw new \Exception('This guard only serves "auth:api".');
  19. });
  20. .
  21. .
  22. .

在 config\auth.php的 guards 数组中添加自定义 guard,一个自定义 guard 包括两部分: driver 和 provider.设置 config\auth.php 的 defaults.guard 为 api

  1. <?php
  2. return [
  3. /*
  4. |--------------------------------------------------------------------------
  5. | Authentication Defaults
  6. |--------------------------------------------------------------------------
  7. |
  8. | This option controls the default authentication "guard" and password
  9. | reset options for your application. You may change these defaults
  10. | as required, but they're a perfect start for most applications.
  11. |
  12. */
  13. 'defaults' => [
  14. 'guard' => 'api',
  15. 'passwords' => 'users',
  16. ],
  17. /*
  18. |--------------------------------------------------------------------------
  19. | Authentication Guards
  20. |--------------------------------------------------------------------------
  21. |
  22. | Next, you may define every authentication guard for your application.
  23. | Of course, a great default configuration has been defined for you
  24. | here which uses session storage and the Eloquent user provider.
  25. |
  26. | All authentication drivers have a user provider. This defines how the
  27. | users are actually retrieved out of your database or other storage
  28. | mechanisms used by this application to persist your user's data.
  29. |
  30. | Supported: "session", "token"
  31. |
  32. */
  33. 'guards' => [
  34. 'web' => [
  35. 'driver' => 'session',
  36. 'provider' => 'users',
  37. ],
  38. 'api' => [
  39. 'driver' => 'token',
  40. 'provider' => 'token',
  41. ],
  42. ],
  43. /*
  44. |--------------------------------------------------------------------------
  45. | User Providers
  46. |--------------------------------------------------------------------------
  47. |
  48. | All authentication drivers have a user provider. This defines how the
  49. | users are actually retrieved out of your database or other storage
  50. | mechanisms used by this application to persist your user's data.
  51. |
  52. | If you have multiple user tables or models you may configure multiple
  53. | sources which represent each model / table. These sources may then
  54. | be assigned to any extra authentication guards you have defined.
  55. |
  56. | Supported: "database", "eloquent"
  57. |
  58. */
  59. 'providers' => [
  60. 'users' => [
  61. 'driver' => 'eloquent',
  62. 'model' => App\Models\User::class,
  63. ],
  64. 'token' => [
  65. 'driver' => 'token',
  66. 'model' => App\Models\User::class,
  67. ],
  68. ],
  69. /*
  70. |--------------------------------------------------------------------------
  71. | Resetting Passwords
  72. |--------------------------------------------------------------------------
  73. |
  74. | You may specify multiple password reset configurations if you have more
  75. | than one user table or model in the application and you want to have
  76. | separate password reset settings based on the specific user types.
  77. |
  78. | The expire time is the number of minutes that the reset token should be
  79. | considered valid. This security feature keeps tokens short-lived so
  80. | they have less time to be guessed. You may change this as needed.
  81. |
  82. */
  83. 'passwords' => [
  84. 'users' => [
  85. 'provider' => 'users',
  86. 'table' => 'password_resets',
  87. 'expire' => 60,
  88. ],
  89. ],
  90. ];
相关推荐
阅读 +