韦德国际1946英国 > 计算机网络 > Auth自定义接口API用户认证的实现方法,Laravel认证

原标题:Auth自定义接口API用户认证的实现方法,Laravel认证

浏览次数:139 时间:2019-07-20

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

IlluminateAuthDatabaseUserProvider

Auth自定义接口API用户认证的实现方法,Laravel认证原理以及完全自定义认证详解。SessionGuard 是 Laravel web 认证暗许的 guard.

Authenticatable 接口

<?php

namespace AppAuth;

use AppModelsUser;
use IlluminateContractsAuthAuthenticatable;
use IlluminateContractsAuthUserProvider as Provider;

class UserProvider implements Provider
{

 /**
 * Retrieve a user by their unique identifier.
 * @param mixed $identifier
 * @return IlluminateContractsAuthAuthenticatable|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 IlluminateContractsAuthAuthenticatable|null
 */
 public function retrieveByToken($identifier, $token)
 {
 return null;
 }

 /**
 * Update the "remember me" token for the given user in storage.
 * @param IlluminateContractsAuthAuthenticatable $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 IlluminateContractsAuthAuthenticatable|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 IlluminateContractsAuthAuthenticatable $user
 * @param array   $credentials
 * @return bool
 */
 public function validateCredentials(Authenticatable $user, array $credentials)
 {
 if ( !isset($credentials['api_token'])) {
 return false;
 }

 return true;
 }
}

Guard 接口

IlluminateContractsAuthAuthenticatable

EloquentUserProvider

在 configauth.php的 guards 数组中增添自定义 guard,三个自定义 guard 包含两有的: driver 和 provider.

DatabaseUserProvider

UserProvider 接口:

一向通过数据库表来获取认证模型.

在 AppServiceProvider 的 boot 方法增加如下代码:

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

贯彻自定义 Guard

'myusers' => [
 'driver' => 'myuserprovider' // 里面具体的字段可以根据你创建 user provider 需要的信息自由添加,可以通过 Auth::createUserProvider('myuserprovider') 创建
],

福寿年高代码如下:

上边 RestApiModel 是大家合营社对 Guzzle 的卷入,用于 php 项目各样系统之间 api 调用. 代码就不方便人民群众透漏了.

StatefulGuard 接口承袭自 Guard 接口,除了 Guard 里面定义的有的中坚接口外,还扩大了更进一竿、有景况的 Guard.

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

图片 1

// 获取唯一标识的,可以用来认证的字段名,比如 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();

Guard 接口

IlluminateAuthEloquentUserProvider

IlluminateAuthAuthenticatable

IlluminateContractsAuthStatefulGuard

Guard 接口定义了有个别完成了 Authenticatable (可验证的) 模型或类的求证方式以及一些常用的接口。

StatefulGuard 接口

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

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

基于上面包车型客车学识,能够领略要自定义一个注解很轻松。

<?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' => AppModelsUser::class,
 ],

 'token' => [
  'driver' => 'token',
  'model' => AppModelsUser::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,
 ],
 ],

];
<?php

namespace AppAuth;

use AppModelsUser;
use IlluminateContractsAuthAuthenticatable;
use IlluminateContractsAuthUserProvider as Provider;

class UserProvider implements Provider
{

 /**
 * Retrieve a user by their unique identifier.
 * @param mixed $identifier
 * @return IlluminateContractsAuthAuthenticatable|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 IlluminateContractsAuthAuthenticatable|null
 */
 public function retrieveByToken($identifier, $token)
 {
 return null;
 }

 /**
 * Update the "remember me" token for the given user in storage.
 * @param IlluminateContractsAuthAuthenticatable $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 IlluminateContractsAuthAuthenticatable|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 IlluminateContractsAuthAuthenticatable $user
 * @param array   $credentials
 * @return bool
 */
 public function validateCredentials(Authenticatable $user, array $credentials)
 {
 if ( !isset($credentials['api_token'])) {
 return false;
 }

 return true;
 }
}

自定义表明

StatefulGuard 接口继承自 Guard 接口,除了 Guard 里面定义的部分宗旨接口外,还扩张了更上一层楼、有动静的 Guard.
新增添长的接口有那个:

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

在 configauth.php的 providers 数组中增多自定义 user provider.

AppAuthUserProvider.php

<?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' => AppModelsUser::class,
 ],

 'token' => [
  'driver' => 'token',
  'model' => AppModelsUser::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 中暗中同意有七个 user provider: DatabaseUserProvider & EloquentUserProvider.

贯彻自定义 Guard

透过 eloquent 模型来得到认证模型

成立三个自定义的 UserProvider,达成 UserProvider 接口,能够回去上边自定义的验证模型;

在 configauth.php的 guards 数组中增多自定义 guard,贰个自定义 guard 包括两有的: driver 和 provider.

RequestGuard 是七个特别轻便的 guard. RequestGuard 是透过传播三个闭包来验证的。能够由此调用 Auth::viaRequest 加多贰个自定义的 RequestGuard.

UserProvider 接口

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

Laravel 中默许有多个 user provider : DatabaseUserProvider & EloquentUserProvider.

IlluminateAuthAuthManager

自定义 Provider

参考小说:地址

Guard 用来讲飞鹤个用户是不是表达成功, UserProvider 用来提供评释模型的源点,而依照项目标 config 管理 guard 以及自定义 guard 等等成效,则是透过 AuthManager 来贯彻。

经过 eloquent 模型来博取认证模型

RequestGuard

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

<?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();
.
.
.
// 尝试根据提供的凭证验证用户是否合法
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();
  • 添加 guard creator 和 user provider creator 到 AuthManager 中

Laravel 中暗中同意有七个 user provider : DatabaseUserProvider & EloquentUserProvider.

<?php

namespace AppAuth;

use IlluminateHttpRequest;
use IlluminateAuthGuardHelpers;
use IlluminateContractsAuthGuard;
use IlluminateContractsAuthUserProvider;

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 IlluminateContractsAuthAuthenticatable|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 IlluminateHttpRequest $request
 * @return $this
 */
 public function setRequest(Request $request)
 {
 $this->request = $request;

 return $this;
 }
}

在 configauth.php的 guards 数组中增多自定义 guard,贰个自定义 guard 包蕴两片段: driver 和 provider.

TokenGuard

兑当代码如下:

Auth facade 对应的达成类就是 AuthManager,AuthManager 在容器中登记为单例,用来保管全部的 guard、user provider 以及 guard 的代办专业。

DatabaseUserProvider

到现在微服务更加的流行了. 比相当多事物都拆分成独立的种类,各类系统之间一向不一贯的关系. 那样大家即使做用户认证断定是联合的做二个单独的 用户认证 系统,并不是各种事情系统都要再度去写一回用户认证相关的东西. 可是又赶过四个标题了. laravel 默许的auth 认证 是基于数据库做的,假设要微服务架构可怎么做吗?

本文由韦德国际1946英国发布于计算机网络,转载请注明出处:Auth自定义接口API用户认证的实现方法,Laravel认证

关键词: 1946伟德国际

上一篇:thinkphp函数学习,系统变量

下一篇:没有了