欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-21 11:14:14
基于 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

<?php

namespace app\auth;

use app\models\user;
use illuminate\contracts\auth\authenticatable;
use illuminate\contracts\auth\userprovider as provider;

class userprovider implements provider
{

 /**
 * retrieve a user by their unique identifier.
 * @param mixed $identifier
 * @return \illuminate\contracts\auth\authenticatable|null
 */
 public function retrievebyid($identifier)
 {
 return app(user::class)::getuserbyguid($identifier);
 }

 /**
 * retrieve a user by their unique identifier and "remember me" token.
 * @param mixed $identifier
 * @param string $token
 * @return \illuminate\contracts\auth\authenticatable|null
 */
 public function retrievebytoken($identifier, $token)
 {
 return null;
 }

 /**
 * update the "remember me" token for the given user in storage.
 * @param \illuminate\contracts\auth\authenticatable $user
 * @param string   $token
 * @return bool
 */
 public function updateremembertoken(authenticatable $user, $token)
 {
 return true;
 }

 /**
 * retrieve a user by the given credentials.
 * @param array $credentials
 * @return \illuminate\contracts\auth\authenticatable|null
 */
 public function retrievebycredentials(array $credentials)
 {
 if ( !isset($credentials['api_token'])) {
 return null;
 }

 return app(user::class)::getuserbytoken($credentials['api_token']);
 }

 /**
 * rules a user against the given credentials.
 * @param \illuminate\contracts\auth\authenticatable $user
 * @param array   $credentials
 * @return bool
 */
 public function validatecredentials(authenticatable $user, array $credentials)
 {
 if ( !isset($credentials['api_token'])) {
 return false;
 }

 return true;
 }
}

authenticatable 接口:

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

<?php
.
.
.
// 获取唯一标识的,可以用来认证的字段名,比如 id,uuid
public function getauthidentifiername();
// 获取该标示符对应的值
public function getauthidentifier();
// 获取认证的密码
public function getauthpassword();
// 获取remember token
public function getremembertoken();
// 设置 remember token
public function setremembertoken($value);
// 获取 remember token 对应的字段名,比如默认的 'remember_token'
public function getremembertokenname();
.
.
.

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

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

实现自定义认证模型

app\models\user.php

<?php

namespace app\models;

use app\exceptions\restapiexception;
use app\models\abstracts\restapimodel;
use illuminate\contracts\auth\authenticatable;

class user extends restapimodel implements authenticatable
{

 protected $primarykey = 'guid';

 public $incrementing = false;

 protected $keytype = 'string';

 /**
 * 获取唯一标识的,可以用来认证的字段名,比如 id,guid
 * @return string
 */
 public function getauthidentifiername()
 {
 return $this->primarykey;
 }

 /**
 * 获取主键的值
 * @return mixed
 */
 public function getauthidentifier()
 {
 $id = $this->{$this->getauthidentifiername()};
 return $id;
 }


 public function getauthpassword()
 {
 return '';
 }

 public function getremembertoken()
 {
 return '';
 }

 public function setremembertoken($value)
 {
 return true;
 }

 public function getremembertokenname()
 {
 return '';
 }

 protected static function getbaseuri()
 {
 return config('api-host.user');
 }

 public static $apimap = [
 'getuserbytoken' => ['method' => 'get', 'path' => 'login/user/token'],
 'getuserbyguid' => ['method' => 'get', 'path' => 'user/guid/:guid'],
 ];


 /**
 * 获取用户信息 (by guid)
 * @param string $guid
 * @return user|null
 */
 public static function getuserbyguid(string $guid)
 {
 try {
 $response = self::getitem('getuserbyguid', [
 ':guid' => $guid
 ]);
 } catch (restapiexception $e) {
 return null;
 }

 return $response;
 }


 /**
 * 获取用户信息 (by token)
 * @param string $token
 * @return user|null
 */
 public static function getuserbytoken(string $token)
 {
 try {
 $response = self::getitem('getuserbytoken', [
 'authorization' => $token
 ]);
 } catch (restapiexception $e) {
 return null;
 }

 return $response;
 }
}

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

guard 接口

illuminate\contracts\auth\guard

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

// 判断当前用户是否登录
public function check();
// 判断当前用户是否是游客(未登录)
public function guest();
// 获取当前认证的用户
public function user();
// 获取当前认证用户的 id,严格来说不一定是 id,应该是上个模型中定义的唯一的字段名
public function id();
// 根据提供的消息认证用户
public function validate(array $credentials = []);
// 设置当前用户
public function setuser(authenticatable $user);

statefulguard 接口

illuminate\contracts\auth\statefulguard

statefulguard 接口继承自 guard 接口,除了 guard 里面定义的一些基本接口外,还增加了更进一步、有状态的 guard.
新添加的接口有这些:

// 尝试根据提供的凭证验证用户是否合法
public function attempt(array $credentials = [], $remember = false);
// 一次性登录,不记录session or cookie
public function once(array $credentials = []);
// 登录用户,通常在验证成功后记录 session 和 cookie 
public function login(authenticatable $user, $remember = false);
// 使用用户 id 登录
public function loginusingid($id, $remember = false);
// 使用用户 id 登录,但是不记录 session 和 cookie
public function onceusingid($id);
// 通过 cookie 中的 remember token 自动登录
public function viaremember();
// 登出
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

<?php

namespace app\auth;

use illuminate\http\request;
use illuminate\auth\guardhelpers;
use illuminate\contracts\auth\guard;
use illuminate\contracts\auth\userprovider;

class userguard implements guard

{
 use guardhelpers;

 protected $user = null;

 protected $request;

 protected $provider;

 /**
 * the name of the query string item from the request containing the api token.
 *
 * @var string
 */
 protected $inputkey;

 /**
 * the name of the token "column" in persistent storage.
 *
 * @var string
 */
 protected $storagekey;

 /**
 * the user we last attempted to retrieve
 * @var
 */
 protected $lastattempted;

 /**
 * userguard constructor.
 * @param userprovider $provider
 * @param request $request
 * @return void
 */
 public function __construct(userprovider $provider, request $request = null)
 {
 $this->request = $request;
 $this->provider = $provider;
 $this->inputkey = 'authorization';
 $this->storagekey = 'api_token';
 }

 /**
 * get the currently authenticated user.
 * @return \illuminate\contracts\auth\authenticatable|null
 */
 public function user()
 {
 if(!is_null($this->user)) {
  return $this->user;
 }

 $user = null;

 $token = $this->gettokenforrequest();

 if(!empty($token)) {
  $user = $this->provider->retrievebycredentials(
  [$this->storagekey => $token]
  );
 }

 return $this->user = $user;
 }

 /**
 * rules a user's credentials.
 * @param array $credentials
 * @return bool
 */
 public function validate(array $credentials = [])
 {
 if (empty($credentials[$this->inputkey])) {
  return false;
 }

 $credentials = [$this->storagekey => $credentials[$this->inputkey]];

 $this->lastattempted = $user = $this->provider->retrievebycredentials($credentials);

 return $this->hasvalidcredentials($user, $credentials);
 }

 /**
 * determine if the user matches the credentials.
 * @param mixed $user
 * @param array $credentials
 * @return bool
 */
 protected function hasvalidcredentials($user, $credentials)
 {
 return !is_null($user) && $this->provider->validatecredentials($user, $credentials);
 }


 /**
 * get the token for the current request.
 * @return string
 */
 public function gettokenforrequest()
 {
 $token = $this->request->header($this->inputkey);

 return $token;
 }

 /**
 * set the current request instance.
 *
 * @param \illuminate\http\request $request
 * @return $this
 */
 public function setrequest(request $request)
 {
 $this->request = $request;

 return $this;
 }
}

在 appserviceprovider 的 boot 方法添加如下代码:

app\providers\authserviceprovider.php

<?php
.
.
.
// auth:api -> token provider.
auth::provider('token', function() {
 return app(userprovider::class);
});

// auth:api -> token guard.
// @throw \exception
auth::extend('token', function($app, $name, array $config) {
 if($name === 'api') {
 return app()->make(userguard::class, [
 'provider' => auth::createuserprovider($config['provider']),
 'request' => $app->request,
 ]);
 }
 throw new \exception('this guard only serves "auth:api".');
});
.
.
.

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

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

<?php

return [

 /*
 |--------------------------------------------------------------------------
 | authentication defaults
 |--------------------------------------------------------------------------
 |
 | this option controls the default authentication "guard" and password
 | reset options for your application. you may change these defaults
 | as required, but they're a perfect start for most applications.
 |
 */

 'defaults' => [
 'guard' => 'api',
 'passwords' => 'users',
 ],

 /*
 |--------------------------------------------------------------------------
 | authentication guards
 |--------------------------------------------------------------------------
 |
 | next, you may define every authentication guard for your application.
 | of course, a great default configuration has been defined for you
 | here which uses session storage and the eloquent user provider.
 |
 | all authentication drivers have a user provider. this defines how the
 | users are actually retrieved out of your database or other storage
 | mechanisms used by this application to persist your user's data.
 |
 | supported: "session", "token"
 |
 */

 'guards' => [
 'web' => [
  'driver' => 'session',
  'provider' => 'users',
 ],

 'api' => [
  'driver' => 'token',
  'provider' => 'token',
 ],
 ],

 /*
 |--------------------------------------------------------------------------
 | user providers
 |--------------------------------------------------------------------------
 |
 | all authentication drivers have a user provider. this defines how the
 | users are actually retrieved out of your database or other storage
 | mechanisms used by this application to persist your user's data.
 |
 | if you have multiple user tables or models you may configure multiple
 | sources which represent each model / table. these sources may then
 | be assigned to any extra authentication guards you have defined.
 |
 | supported: "database", "eloquent"
 |
 */

 'providers' => [
 'users' => [
  'driver' => 'eloquent',
  'model' => app\models\user::class,
 ],

 'token' => [
  'driver' => 'token',
  'model' => app\models\user::class,
 ],
 ],

 /*
 |--------------------------------------------------------------------------
 | resetting passwords
 |--------------------------------------------------------------------------
 |
 | you may specify multiple password reset configurations if you have more
 | than one user table or model in the application and you want to have
 | separate password reset settings based on the specific user types.
 |
 | the expire time is the number of minutes that the reset token should be
 | considered valid. this security feature keeps tokens short-lived so
 | they have less time to be guessed. you may change this as needed.
 |
 */

 'passwords' => [
 'users' => [
  'provider' => 'users',
  'table' => 'password_resets',
  'expire' => 60,
 ],
 ],

];

使用 方式:

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

参考文章:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。