Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页 [英] Laravel using web authentication in all api routes redirect to home
问题描述
我想对所有 api 路由使用 Web 身份验证.我创建了中间件,这就是它的样子
i want to use web authentication for all api routes. I created middleware and this is how it looks like
Route::group(['middleware' => ['auth:web'], 'prefix' => 'v1',], function ($router) {
Route::apiResource('subscriptions', 'Api\SubscriptionController');
Route::post('subscriptions/{id}/resend', 'Api\SubscriptionController@resend')->name('resend');
Route::post('subscriptions/{id}/grace', 'Api\SubscriptionController@addGrace')->name('grace');
Route::apiResource('accounts', 'Api\SocialMediaAccountController');
Route::post('accounts/{id}/reset', 'Api\SocialMediaAccountController@reset');
Route::apiResource('customers', 'Api\CustomerController');
});
当我已经登录并尝试向 api 路由发出请求时,它会将我重定向到主页.我怎样才能解决这个问题 ?
When i am already logged in and i try to make request to api route, it redirect me to the home page. How can i fix this ?
这里是 config/auth.php
Here is the config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
如果我已经登录,我不希望重定向 api 路由.我只想进行网络授权并继续执行相同的请求.
I don't want api routes to be redirected if i am already logged in. I just want to do web authorization and continue with same request.
推荐答案
只需两个更新即可限制您的 api 路由,以要求您的 Web 身份验证会话发出 api 请求.
Just two updates to restrict your api routes to require your web auth session to make api requests.
- 将中间件从
api
更新为web
.
- Update middleware from
api
toweb
.
# File: app/Providers/RouteServiceProvider.php
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('web') # <-- CHANGE to 'web'
->namespace($this->namespace."\\API")
->group(base_path('routes/api.php'));
}
- 将中间件从
auth:api
更新为auth:web
(或简单的auth
)
- Update middleware from
auth:api
toauth:web
(or simplyauth
)
# routes/api.php
Route::middleware('auth:web')->get('/user', function (Request $request) {
return $request->user();
});
这篇关于Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!