主頁 > 知識庫 > 基于Laravel Auth自定義接口API用戶認證的實現(xiàn)方法

基于Laravel Auth自定義接口API用戶認證的實現(xiàn)方法

熱門標簽:代理打電話機器人 企業(yè)400電話辦理多少費用 太原400電話申請流程 桂陽公司如何做地圖標注 宿州正規(guī)外呼系統(tǒng)軟件 合肥企業(yè)外呼系統(tǒng)線路 神龍斗士電話機器人 電信外呼系統(tǒng)多少錢一個月 萍鄉(xiāng)商鋪地圖標注

基于 laravel 默認的 auth 實現(xiàn) api 認證

現(xiàn)在微服務越來越流行了. 很多東西都拆分成獨立的系統(tǒng),各個系統(tǒng)之間沒有直接的關系. 這樣我們?nèi)绻鲇脩粽J證肯定是統(tǒng)一的做一個獨立的 用戶認證 系統(tǒng),而不是每個業(yè)務系統(tǒng)都要重新去寫一遍用戶認證相關的東西. 但是又遇到一個問題了. laravel 默認的auth 認證 是基于數(shù)據(jù)庫做的,如果要微服務架構(gòu)可怎么做呢?

實現(xiàn)代碼如下:

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

直接通過數(shù)據(jù)庫表來獲取認證模型.

EloquentUserProvider

Illuminate\Auth\EloquentUserProvider

通過 eloquent 模型來獲取認證模型

根據(jù)上面的知識,可以知道要自定義一個認證很簡單。

自定義 Provider

創(chuàng)建一個自定義的認證模型,實現(xiàn) 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 定義了一個可以被用來認證的模型或類需要實現(xiàn)的接口,也就是說,如果需要用一個自定義的類來做認證,需要實現(xiàn)這個接口定義的方法。

?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 模型的這些方法可以修改一些設置。

實現(xiàn)自定義認證模型

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 項目各個系統(tǒng)之間 api 調(diào)用. 代碼就不方便透漏了.

Guard 接口

Illuminate\Contracts\Auth\Guard

Guard 接口定義了某個實現(xiàn)了 Authenticatable (可認證的) 模型或類的認證方法以及一些常用的接口。

// 判斷當前用戶是否登錄
public function check();
// 判斷當前用戶是否是游客(未登錄)
public function guest();
// 獲取當前認證的用戶
public function user();
// 獲取當前認證用戶的 id,嚴格來說不一定是 id,應該是上個模型中定義的唯一的字段名
public function id();
// 根據(jù)提供的消息認證用戶
public function validate(array $credentials = []);
// 設置當前用戶
public function setUser(Authenticatable $user);

StatefulGuard 接口

Illuminate\Contracts\Auth\StatefulGuard

StatefulGuard 接口繼承自 Guard 接口,除了 Guard 里面定義的一些基本接口外,還增加了更進一步、有狀態(tài)的 Guard.
新添加的接口有這些:

// 嘗試根據(jù)提供的憑證驗證用戶是否合法
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 是通過傳入一個閉包來認證的??梢酝ㄟ^調(diào)用 Auth::viaRequest 添加一個自定義的 RequestGuard.

SessionGuard

Illuminate\Auth\SessionGuard

SessionGuard 是 Laravel web 認證默認的 guard.

TokenGuard

Illuminate\Auth\TokenGuard

TokenGuard 適用于無狀態(tài) api 認證,通過 token 認證.

實現(xiàn)自定義 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 數(shù)組中添加自定義 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,
 ],
 ],

];

使用 方式:


參考文章:地址

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

您可能感興趣的文章:
  • laravel框架 api自定義全局異常處理方法
  • 基于laravel制作APP接口(API)
  • 詳解Laravel5.6 Passport實現(xiàn)Api接口認證
  • 詳解laravel安裝使用Passport(Api認證)
  • laravel dingo API返回自定義錯誤信息的實例
  • 在 Laravel 中動態(tài)隱藏 API 字段的方法
  • Laravel如何實現(xiàn)適合Api的異常處理響應格式

標簽:廊坊 綏化 衡陽 辛集 白銀 太原 鄂州 崇左

巨人網(wǎng)絡通訊聲明:本文標題《基于Laravel Auth自定義接口API用戶認證的實現(xiàn)方法》,本文關鍵詞  基于,Laravel,Auth,自定義,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《基于Laravel Auth自定義接口API用戶認證的實現(xiàn)方法》相關的同類信息!
  • 本頁收集關于基于Laravel Auth自定義接口API用戶認證的實現(xiàn)方法的相關信息資訊供網(wǎng)民參考!
  • 推薦文章