Laravel5.5學習筆記之框架自帶API Token認證


框架自帶Token認證

    1. 需要在用戶表加api_token字段
  • 2.路由配置

登錄注冊等省略,詳細參考文檔
https://laravelacademy.org/post/9153.html#toc_12

    1. 配置需要認證的路由
Route::group(['middleware'=>'auth:api'],function(){
    Route::any('user', function (Request $request) {
        return $request->user();
    });
});

上面需要認證通過,才能拿到用戶的Token信息

['middleware'=>'auth:api'] 這段配置的意思:

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

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

路由中間件: 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 對應的配置文件 auth.php auth.guards.api

dirver 文件是token 對應的是框架的:

 vendor/laravel/framework/src/Illuminate/Auth/TokenGuard.php

   vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php


獲取Token 的方法,從header里面獲取

  public function getTokenForRequest()
    {

        $token = $this->request->query($this->inputKey);
        if (empty($token)) {
            $token = $this->request->input($this->inputKey);
        }
        if (empty($token)) {
            $token = $this->request->bearerToken();
        }
        if (empty($token)) {
            $token = $this->request->getPassword();
        }

        return $token;
    }

    /**
     * Get the bearer token from the request headers.
     *
     * @return string|null
     */
    public function bearerToken()
    {
        $header = $this->header('Authorization', '');

        if (Str::startsWith($header, 'Bearer ')) {
            return Str::substr($header, 7);
        }
    }

由此可知框架從header里面獲取默認的字段是Authorization ,且字段值是 Bearer api_token,如下圖

開始沒有看源碼測試了 api_toke, token,Authorization 都試過不可以(其實Authorization 這個是可以的)

不可以的原因是因為,路由配置是get請求,結果代碼里面是post請求導致路由異常

Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException

參考:

https://segmentfault.com/a/1190000018245349

https://learnku.com/articles/11006/detailed-explanation-of-laravels-own-api-guard-drive-token

訪問用戶

https://laravelacademy.org/post/9153.html#toc_12
$request->user() 或 Auth 門面訪問當前用戶:
Auth::guard('api')->user(); // 登錄用戶實例
Auth::guard('api')->check(); // 用戶是否登錄
Auth::guard('api')->id(); // 登錄用戶ID

中間件

Location of auth:api Middleware

It's not a good idea to edit vendor files

https://stackoverflow.com/questions/53716751/location-of-authapi-middleware


免責聲明!

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



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