在Laravel 8 REST API中應用JSON Web Token (JWT)

Yu-Cheng Hung
13 min readMar 3, 2021

--

各位讀者們好,前陣子Laravel更新至8版且有讀者詢問是否有相關的JWT應用範例,因此我也試著研究了一下在Laravel 8中如何應用JWT驗證,算是承接前篇文章 – 在Laravel 6 REST API中應用JSON Web Token (JWT) ,那麼就開始本次的內容吧!

首先建立一個全新的 Laravel 8 project

composer create-project laravel/laravel laravel-jwt-auth --prefer-dist

在MySQL中新建一個 database: laravel_db

並且修改 .env 檔案中的 db 名稱(名稱可自由設定)

執行 migration

php artisan migrate

此時查看db,應會是如下的結構(此為HeidiSQL)

接著安裝 jwt package

composer require tymon/jwt-auth

完成後至 config/app.php 將 laravel service provider 和 JWTAuth、JWTFactory include 進去

'providers' => [
....
....
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
'aliases' => [
....
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
....
],

設定 config/jwt.php

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

產生 secret key

php artisan jwt:secret

成功後可在 .env 中看到如下的畫面

修改 app/Models/User.php,加入兩個function:getJWTIdentifier() 和 getJWTCustomClaims()

<?phpnamespace App\Models;use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];

/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier() {
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims() {
return [];
}
}

注意上方要use JWTSubject,class 宣告時要 implements JWTSubject

接著修改 config/auth.php

<?phpreturn ['defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],

建立 Authentication Controller

php artisan make:controller AuthController

將下列 functions 加入 app/Http/Controllers/AuthController.php

<?phpnamespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Validator;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh() {
return $this->createNewToken(auth()->refresh());
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function userProfile() {
return response()->json(auth()->user());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
}

設定 routes/api.phproutes/api.php

<?phpuse Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/refresh', [AuthController::class, 'refresh']);
Route::get('/user-profile', [AuthController::class, 'userProfile']);
});

以上就是設定和修改的部分,接著用 Postman 來進行行為測試

讀者們可選擇用 php artisan serve 或者 xampp 的方式啟動專案,筆者這邊選擇用 xampp 並設定 port 為 1106

測試一:使用者註冊

測試二:使用者登入,登入成功即回應 access token

測試三:以 JWT token 取得user profile

測試四:更新 JWT token,取得綠框中新的 token

測試五:使用者登出,移除 JWT token

以上就是測試的方式及畫面,完整程式碼github如下:

https://github.com/rommelhong/jwt-laravel8

本篇內容參考:https://www.positronx.io/laravel-jwt-authentication-tutorial-user-login-signup-api/

謝謝大家!

--

--