Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页

2024-02-12

我想对所有 api 路由使用网络身份验证。我创建了中间件,它是这样的

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 路由发出请求时,它会将我重定向到主页。我怎样才能解决这个问题 ?

这是 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 路由被重定向。我只想进行 Web 授权并继续执行相同的请求。


只需两个更新即可限制您的 api 路由,要求您的 Web 身份验证会话发出 api 请求。

  1. 更新中间件api to web.
# 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'));

    }
  1. 更新中间件auth:api to auth:web(或者简单地auth)
# routes/api.php
Route::middleware('auth:web')->get('/user', function (Request $request) {
     return $request->user();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页 的相关文章

随机推荐