Route::group(['middleware' => ['auth:api', 'custom.guard']], function () {
// your protected routes here
});
app/Providers/AuthServiceProvider.php
中注册自定义守卫和护照:public function boot()
{
$this->registerPolicies();
Auth::provider('custom', function ($app, array $config) {
return new CustomUserProvider($app->make('hash'), $config['model']);
});
Auth::extend('custom.guard', function ($app, $name, array $config) {
return new CustomGuard(Auth::createUserProvider($config['provider']), $app->make('request'));
});
}
这里的CustomUserProvider
代表自定义用户提供程序,CustomGuard
代表自定义守卫。
3. 在自定义守卫中覆盖authenticate
方法,并在验证失败时返回JSON响应:
public function authenticate(Request $request)
{
if ($this->auth->guard('api')->check()) {
return $this->auth->shouldUse('api');
}
$user = $this->auth->setRequest($request)->user('custom');
if ($user) {
$this->auth->login($user);
return $this->auth->user();
}
return response()->json(['error' => 'Unauthorized'], 401);
}
Route::group(['middleware' => ['auth:api', 'custom.guard']], function () {
return response()->json(['message'=> 'This is a protected API route']);
});