Laravel JWT是一個基於JWT(JSON Web Token)的Laravel身份驗證和授權包。JWT作為一種輕量級的身份驗證和授權解決方案,在Web應用程序中越來越受歡迎。本文將從多個方面對Laravel JWT進行詳細闡述。
一、安裝和配置
1、安裝和配置Laravel JWT非常簡單,首先您需要使用composer安裝Laravel JWT:
composer require tymon/jwt-auth
2、安裝成功後,您需要發布配置文件以及一些必要的文件:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
3、在.env文件中添加一個密鑰以用於JWT加密和解密:
JWT_SECRET=your-secret-key
4、接下來您需要對config/auth.php進行修改,將默認的guard和provider設置為JWT:
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
二、認證和授權
1、Laravel JWT提供了一個auth:api中間件,我們可以使用它來保護我們的API路由,只有經過身份驗證的用戶才能訪問被保護的路由。
2、在您的路由文件中使用auth:api中間件來保護需要身份驗證的路由:
Route::group(['middleware' => 'auth:api'], function () {
Route::get('/profile', 'UserController@profile');
Route::post('/logout', 'AuthController@logout');
});
3、Laravel JWT還提供了一個jwt.auth中間件,我們可以使用它來手動驗證JWT並獲取當前用戶。只需要在需要手動驗證JWT的方法中使用jwt.auth中間件即可:
public function profile()
{
$user = JWTAuth::parseToken()->authenticate();
return response()->json(['user' => $user]);
}
4、Laravel JWT還提供了jwt.auth和jwt.refresh路由,我們可以使用它們來獲取新的JWT令牌或者刷新過期的JWT令牌:
Route::group(['middleware' => 'api', 'prefix' => 'auth'], function ($router) {
Route::post('login', 'AuthController@login');
Route::post('refresh', 'AuthController@refresh');
Route::post('logout', 'AuthController@logout');
});
5、最後是用戶註冊和登錄的方法:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (!$token = Auth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function register(Request $request)
{
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
$user->save();
$token = Auth::fromUser($user);
return $this->respondWithToken($token, 201);
}
三、JWT黑名單
1、Laravel JWT提供了一個JWT黑名單,我們可以使用它來撤銷JWT。當一個JWT被加入到黑名單中,它就不能再被使用。
2、使用Laravel JWT的JWT黑名單需要進行以下配置:
(1)在config/jwt.php文件中將denylist中間件的啟用狀態設置為true:
'denylist_enabled' => true,
(2)在config/jwt.php文件中配置JWT黑名單的時間:
'ttl' => env('JWT_TTL', 60),
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),
(3)運行以下命令進行JWT黑名單的遷移:
php artisan jwt:secret
php artisan jwt:blacklist:install
3、現在您可以在需要撤銷JWT的時候使用以下方法:
public function logout(Request $request)
{
JWTAuth::invalidate($request->bearerToken());
return response()->json(['message' => 'Successfully logged out']);
}
四、自定義響應
1、默認情況下,Laravel JWT返回的響應是JSON格式的,如果您需要自定義響應格式或者添加一些額外的響應頭(如Token-Expired),您可以自己定義RespondWithToken方法:
protected function respondWithToken($token, $code = 200)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => JWTAuth::factory()->getTTL() * 60
], $code);
}
2、在您的控制器方法中使用respondWithToken方法來自定義響應:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (!$token = Auth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
五、總結
本文詳細闡述了如何使用Laravel JWT進行基於JWT的身份驗證和授權。從安裝和配置、認證和授權、JWT黑名單和自定義響應等多個方面講解了Laravel JWT的使用方法和注意事項。希望本文能夠幫助您更好地使用Laravel JWT。
原創文章,作者:DSOHJ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/368130.html