一、背景
tymon/jwt-auth是一個基於JWT認證和Laravel框架而開發的PHP庫,驗證JWT令牌並通過Eloquent ORM提供對數據庫支持。 JWT是在應用程序中生成,簽名,並將其用作用戶或客戶端的身份驗證標識符的 JSON 負載。
二、使用
tymon/jwt-auth是一個易於安裝和使用的庫,它可以輕鬆地為您的Laravel應用程序提供JWT認證。您需要先在您的 Laravel 應用程序中安裝 tymon/jwt-auth 包,使用 Composer,以便可以輕鬆應用 JWT 認證。
三、安裝
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
在 config/auth.php 配置文件中配置 guards 和 providers
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
]
],
確保在您的 User 模型中包含 JWTSubject 受到支持的接口,以便在生成JWT令牌時包括正確的所有信息。
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
// ...
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
四、認證
在jwt-auth中,認證過程主要分為兩部分:生成JWT令牌和驗證JWT令牌。
1、生成JWT令牌
Successful authentication will return a token string that should be sent to the client alongside their authenticated user data. This token can be used to authenticate subsequent requests to any part of your application that requires authentication.
only(['email', 'password']);
if (!$token = Auth::attempt($credentials)) {
return response()->json(['message' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* 返回JWT token
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
?>
2、驗證JWT令牌
JWT tokens sent with requests to your application should be included in the Authorization header using the Bearer authentication scheme.
json(['users' => $users]);
}
}
?>
五、更多功能
1、自定義響應
可以使用JWT-auth自定義響應,只需在 config/jwt.php 配置文件中添加以下內容:
'custom' => [
'claim_to_return' => 'value_to_return',
'user_object' => 'App\\User',
'some_value' => 'some_value',
],
發出響應時,JWT-auth將發佈此對象:
{'some_value': 'some_value', 'claim_to_return': 'value_to_return', 'user_object': { ... }}
2、更新令牌
public function refresh() {
$token = JWTAuth::getToken();
try {
$token = JWTAuth::refresh($token);
} catch (TokenExpiredException $e) {
throw new HttpResponseException(response()->json([
'token_expired'
], $e->getStatusCode()));
} catch (JWTException $e) {
throw new HttpResponseException(response()->json([
'token_invalid'
], $e->getStatusCode()));
}
return response()->json([
'token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
3、各平台的Token格式
JWTAuth::fromUser($user, [
'platform' => 'ios'
])
總結
通過學習tymon/jwt-auth和JWT認證,我們可以輕鬆實現Laravel API應用程序的身份驗證,確保在您的API應用程序中使用保護的路由時,用戶必須登錄並提供正確的憑據。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/150483.html