您好,登錄后才能下訂單哦!
在Laravel中構建一個高效的API認證系統,支持Token刷新和吊銷可以通過以下步驟實現:
使用Laravel Passport來實現OAuth2.0認證授權機制,它提供了一種簡單而強大的API認證方案。
安裝Passport插件:
composer require laravel/passport
php artisan passport:install
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Route::post('/login', 'AuthController@login');
Route::post('/refresh', 'AuthController@refresh');
Route::post('/logout', 'AuthController@logout')->middleware('auth:api');
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('MyApp')->accessToken;
return response()->json(['token' => $token]);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
public function refresh(Request $request)
{
$user = Auth::user();
$token = $user->createToken('MyApp')->accessToken;
return response()->json(['token' => $token]);
}
public function logout(Request $request)
{
$user = Auth::user();
$user->token()->revoke();
return response()->json(['message' => 'Successfully logged out']);
}
}
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
}
'api' => [
'throttle:api',
'auth:api',
],
Authorization: Bearer {token}
通過以上步驟,就可以構建一個基于Laravel Passport的高效API認證系統,支持Token刷新和吊銷的功能。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。