您好,登錄后才能下訂單哦!
在Laravel中構(gòu)建一個(gè)高效的API認(rèn)證系統(tǒng),支持Token刷新和吊銷可以通過以下步驟實(shí)現(xiàn):
使用Laravel Passport來實(shí)現(xiàn)OAuth2.0認(rèn)證授權(quán)機(jī)制,它提供了一種簡(jiǎn)單而強(qiáng)大的API認(rèn)證方案。
安裝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}
通過以上步驟,就可以構(gòu)建一個(gè)基于Laravel Passport的高效API認(rèn)證系統(tǒng),支持Token刷新和吊銷的功能。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。