在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。