[PHP] 淺談 Laravel Authentication 的 auth:api


 

auth:api 在 Laravel 的 Routing , Middleware , API Authentication 主題中都有出現。

 

一.

在 Routing 部分可以知道 auth:api 是中間件的名字,代表某個中間件實現,使用方式為 Route::middleware('auth:api')。

 

二.

在 Middleware 部分可以知道 auth:api 冒號后面的是 中間件參數,多個參數就用逗號分隔,也就是說 'api' 是 auth 中間件的參數。auth 中間件在 app/Http/Kernel.php 的路由中間件里定義:protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class ]。

 

Middleware 中間件都是在 handle 方法里對請求進行驗證的,handle 前面兩個參數是 $request, Closure $next。中間件參數在 handle 的默認參數后面,例如 user:creater,editer 就表示 user 中間件的 handle 方法的第三個參數值是 creater, 第四個參數值是 editer。

對於 Auth 中間件來說,參數值 api 表示所使用的 guard 是 api,我們可以看其所繼承的父類實現:

// Illuminate\Auth\Middleware\Authenticate->handle()

public function handle($request, Closure $next, ...$guards)
{
    $this->authenticate($request, $guards);

    return $next($request);
}

里面的驗證所使用的就是下面要講的 Auth 功能類(AuthManager)。當驗證不通過,會拋出 AuthenticationException。

 

默認的 app/Http/Middleware/Authenticate 包含一個 redirectTo 方法,當我們構建 api 應用時,驗證未通過並不需要重定向。

那么可以注釋掉 redirectTo,然后在 handler.php 中處理 AuthenticationException。

 

三.

在 API Authentication 部分,config/auth.php 配置有多個 guards,分別有自己的 driver 和 providers。

另外 Auth Facade (AuthManager) 提供了 Auth::guard() 方法用於決定 Auth 所使用的 guard。

Auth(Facade)提供了統一的方法來處理用戶認證檢測、驅動的擴展,通過更改配置而不是代碼來使用不同的驅動。

Auth 內置了兩種驅動的實現,AuthManager->createSessionDriver($name, $config), AuthManager->createTokenDriver($name, $config)。

 

如果你想更進一步了解 API Authentication 的運行過程,建議閱讀一下 createTokenDriver() 內部實例化的 TokenGuard 類。

TokenGuard 會順序檢測 "query request"、"input request"、"header 鍵為 Authentication 值為 bearer xxx",從中獲取 token 值;接着根據配置中的 provider 的值創建 provider 具體實例來驗證 token。

 

有關 auth:api 與 Auth 的意義大致如此。

 

相關:[PHP] 淺談 Laravel Authentication 的 guards 與 providers

相關:[PHP] 淺談 Laravel auth:api 不同驅動 token 和 passport 的區別

相關:[PHP] 淺談 Laravel 三大驗證方式的區別, auth:api, passport, auth:airlock

Link:https://www.cnblogs.com/farwish/p/11800803.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM