2020-11-08|閱讀時間 ‧ 約 10 分鐘

Laravel Restful API with JWT Authentication

本筆記遵循官方文件教學,經過一些小修改,經測試可以跑在Laravel Framework version: 8.13.0,將筆記記錄下來。

Laravel installation
1. 使用composer安裝JWT:
如同這邊提到的: https://github.com/tymondesigns/jwt-auth/releases/tag/1.0.1 tymon/jwt-auth這個jwt套件目前最新版本為1.0.1,兼容支援Laravel 8。 在專案目錄下,下這個指令來安裝指定版本: $ composer require tymon/jwt-auth "1.0.1"
2. Publish the config
發佈軟件包配置文件: $ php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
執行指令完畢後,會在config folder中產生一個jwt.php檔案,裡面有一些基本設定。
3. 產生secret key $ php artisan jwt:secret
這個指令會更新.env檔案,新增類似JWT_SECRET=foobar的東西。 這個secret key是用來簽署token的,根據選擇的演算法來簽名。

Quick start
1. 更新user model
加入 (1)use Tymon\JWTAuth\Contracts\JWTSubject; (2) implements JWTSubject (3) getJWTIdentifier(), getJWTCustomClaims()兩個method。 (4) table name若不是users,記得改一下。
2. Configure Auth guard
修改config/auth.php,原本為:
改為如紅框這樣:
3. 新增基本認證Routes
在routes/api.php加入:
use App\Http\Controllers\AuthController;

Route::group([
      'middleware' => 'api',
      'prefix' => 'user'
    ], function ($router) {
      Route::post('login', [AuthController::class, 'login']);
      Route::post('logout', [AuthController::class, 'logout']);
      Route::post('refresh', [AuthController::class, 'refresh']);
      Route::post('me', [AuthController::class, 'me']);
});
4. 建立AuthController $ php artisan make:controller AuthController
其中__construct中的那一行,意思是除了login這個method以外,其他api都要帶上access token才能存取! $this-middleware('auth:api')=表示使用auth middleware,傳入api參數。
5.Config DB
參考Laravel 8 Hello World這篇,不再贅述。
6.測試JWT
現在可以post到login這個endpoint測試看看: http://localhost/laravel_jwt/public/api/user/login
可以看到在登入成功後,server會response一組access token給前端。 其中,在AuthController的login method中驗證使用者帳密,需特別注意資料庫中的密碼要使用BCrypt演算法來加密,如上圖該密碼即為123加密後的結果。
登入後,打http://localhost/laravel_jwt/public/api/user/me,header中帶上Authorization: Bearer ${access_token},就可以拿到user資料了!
在登入狀態下refresh,可以換新token: http://localhost/laravel_jwt/public/api/user/refresh
接著測試登出:http://localhost/laravel_jwt/public/api/user/logout 由於剛剛有refresh,token要換成新的。
值得一提的是,在login之後,所有其他api(me/logout/refresh),都須在header帶上access token,才能存取。

最後我們新增一個文章api,來測試看看。
建構子中這行$this-middleware('auth:api'); = 表示使用auth middleware,傳入api參數。 所以會先經過中間層,來驗證前端有無帶正確token過來。
這個middleware其實是定義在這:
然後我們打一下article api,故意不帶token:
這是因為L18這行出現exception,為了讓api 更完善,修改一下app\Http\Middleware\Authenticate.php:
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    protected function authenticate($request, array $guards){
        try{
            parent::authenticate($request, $guards);
        } catch (AuthenticationException $e){
            throw new UnauthorizedHttpException('JWTAuth', $e->getMessage());
        }
    }
}

再改一下app\Exceptions\Handler.php,加入紅框程式碼:
use Illuminate\Auth\AuthenticationException;
protected function unauthenticated($request, AuthenticationException $exception){
        return response()->json(['error' => 'Unauthenticated.'], 401);
}
接著我們打一下article api,故意不帶token,或者token故意帶錯誤的:
這樣處理看起來好多了,沒帶token或者token錯誤都會回401。

後記:
若要改User model name,可在config/auth.php中找到這段User::class,改成你的Xxx::class。
AuthController login method 中的 auth()-attempt($credentials),就是直接拿這邊設定的model data來驗證。

若遇到這個錯誤: TypeError: Argument 3 passed to Lcobucci\JWT\Signer\Hmac::doVerify() must be an instance of Lcobucci\JWT\Signer\Key, null given
解法: $ php artisan key:generate $ php artisan jwt:secret

分享至
成為作者繼續創作的動力吧!
小弟是一位軟體工程師,樂於幫助他人,撰寫技術文章除了幫助自己複習以外,也希望可以幫助到他人,若文章內容有誤,還請大大不吝給予指教!
© 2024 vocus All rights reserved.