当前位置:首页 > CMS教程 > 其它CMS > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-10-10 13:46:52 浏览: 评论:0 

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

基于 laravel 默认的 auth 实现 api 认证

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

实现代码如下:

UserProvider 接口:

通过唯一标示符获取认证模型

public function retrieveById($identifier);

通过唯一标示符和 remember token 获取模型

public function retrieveByToken($identifier, $token);

通过给定的认证模型更新 remember token

public function updateRememberToken(Authenticatable $user, $token);

通过给定的凭证获取用户,比如 email 或用户名等等

public function retrieveByCredentials(array $credentials);

认证给定的用户和给定的凭证是否符合

public function validateCredentials(Authenticatable $user, array $credentials);

Laravel 中默认有两个 user provider : DatabaseUserProvider & EloquentUserProvider.

DatabaseUserProvider

Illuminate\Auth\DatabaseUserProvider

直接通过数据库表来获取认证模型.

EloquentUserProvider

Illuminate\Auth\EloquentUserProvider

通过 eloquent 模型来获取认证模型

根据上面的知识,可以知道要自定义一个认证很简单。

自定义 Provider

创建一个自定义的认证模型,实现 Authenticatable 接口;

App\Auth\UserProvider.php

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

Authenticatable 接口:

Illuminate\Contracts\Auth\Authenticatable

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

  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(); 

Laravel 中定义的 Authenticatable trait,也是 Laravel auth 默认的 User 模型使用的 trait,这个 trait 定义了 User 模型默认认证标示符为 'id',密码字段为password,remember token 对应的字段为 remember_token 等等。

通过重写 User 模型的这些方法可以修改一些设置。

实现自定义认证模型

App\Models\User.php

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

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

Guard 接口

Illuminate\Contracts\Auth\Guard

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

  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); 

StatefulGuard 接口

Illuminate\Contracts\Auth\StatefulGuard

StatefulGuard 接口继承自 Guard 接口,除了 Guard 里面定义的一些基本接口外,还增加了更进一步、有状态的 Guard.

新添加的接口有这些:

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

Laravel 中默认提供了 3 中 guard :RequestGuard,TokenGuard,SessionGuard.

RequestGuard

Illuminate\Auth\RequestGuard

RequestGuard 是一个非常简单的 guard. RequestGuard 是通过传入一个闭包来认证的,可以通过调用 Auth::viaRequest 添加一个自定义的 RequestGuard.

SessionGuard

Illuminate\Auth\SessionGuard

SessionGuard 是 Laravel web 认证默认的 guard.

TokenGuard

Illuminate\Auth\TokenGuard

TokenGuard 适用于无状态 api 认证,通过 token 认证.

实现自定义 Guard

App\Auth\UserGuard.php

  1. <?php 
  2.  
  3. namespace App\Auth; 
  4.  
  5. use Illuminate\Http\Request; 
  6. use Illuminate\Auth\GuardHelpers; 
  7. use Illuminate\Contracts\Auth\Guard; 
  8. use Illuminate\Contracts\Auth\UserProvider; 
  9.  
  10. class UserGuard implements Guard 
  11.  
  12. { 
  13.  use GuardHelpers; 
  14.  
  15.  protected $user = null; 
  16.  
  17.  protected $request; 
  18.  
  19.  protected $provider; 
  20.  
  21.  /** 
  22.  * The name of the query string item from the request containing the API token. 
  23.  * 
  24.  * @var string 
  25.  */ 
  26.  protected $inputKey; 
  27.  
  28.  /** 
  29.  * The name of the token "column" in persistent storage. 
  30.  * 
  31.  * @var string 
  32.  */ 
  33.  protected $storageKey; 
  34.  
  35.  /** 
  36.  * The user we last attempted to retrieve 
  37.  * @var 
  38.  */ 
  39.  protected $lastAttempted; 
  40.  
  41.  /** 
  42.  * UserGuard constructor. 
  43.  * @param UserProvider $provider 
  44.  * @param Request $request 
  45.  * @return void 
  46.  */ 
  47.  public function __construct(UserProvider $provider, Request $request = null) 
  48.  { 
  49.  $this->request = $request; 
  50.  $this->provider = $provider; 
  51.  $this->inputKey = 'Authorization'; 
  52.  $this->storageKey = 'api_token'; 
  53.  } 
  54.  
  55.  /** 
  56.  * Get the currently authenticated user. 
  57.  * @return \Illuminate\Contracts\Auth\Authenticatable|null 
  58.  */ 
  59.  public function user() 
  60.  { 
  61.  if(!is_null($this->user)) { 
  62.   return $this->user; 
  63.  } 
  64.  
  65.  $user = null; 
  66.  
  67.  $token = $this->getTokenForRequest(); 
  68.  
  69.  if(!emptyempty($token)) { 
  70.   $user = $this->provider->retrieveByCredentials( 
  71.   [$this->storageKey => $token] 
  72.   ); 
  73.  } 
  74.  
  75.  return $this->user = $user; 
  76.  } 
  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 (emptyempty($credentials[$this->inputKey])) { 
  86.   return false; 
  87.  } 
  88.  
  89.  $credentials = [$this->storageKey => $credentials[$this->inputKey]]; 
  90.  
  91.  $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); 
  92.  
  93.  return $this->hasValidCredentials($user, $credentials); 
  94.  } 
  95.  
  96.  /** 
  97.  * Determine if the user matches the credentials. 
  98.  * @param mixed $user 
  99.  * @param array $credentials 
  100.  * @return bool 
  101.  */ 
  102.  protected function hasValidCredentials($user, $credentials) 
  103.  { 
  104.  return !is_null($user) && $this->provider->validateCredentials($user, $credentials); 
  105.  } 
  106.  
  107.  
  108.  /** 
  109.  * Get the token for the current request. 
  110.  * @return string 
  111.  */ 
  112.  public function getTokenForRequest() 
  113.  { 
  114.  $token = $this->request->header($this->inputKey); 
  115.  
  116.  return $token; 
  117.  } 
  118.  
  119.  /** 
  120.  * Set the current request instance. 
  121.  * 
  122.  * @param \Illuminate\Http\Request $request 
  123.  * @return $this 
  124.  */ 
  125.  public function setRequest(Request $request) 
  126.  { 
  127.  $this->request = $request; 
  128.  
  129.  return $this; 
  130.  } 
  131. } 

在 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.  
  10. // auth:api -> token guard. 
  11. // @throw \Exception 
  12. Auth::extend('token', function($app, $name, array $config) { 
  13.  if($name === 'api') { 
  14.  return app()->make(UserGuard::class, [ 
  15.  'provider' => Auth::createUserProvider($config['provider']), 
  16.  'request' => $app->request, 
  17.  ]); 
  18.  } 
  19.  throw new \Exception('This guard only serves "auth:api".'); 
  20. }); 
  21. . 
  22. . 
  23. . 

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

设置 config\auth.php 的 defaults.guard 为 api.

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

Tags: Auth API

分享到: