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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52166907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:01:33  来源:igfitidea点击:

Laravel using web authentication in all api routes redirect to home

phplaravelapiauthenticationauthorization

提问by Miljan Rakita

i want to use web authentication for all api routes. I created middleware and this is how it looks like

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

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');
});

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 ?

当我已经登录并尝试向 api 路由发出请求时,它会将我重定向到主页。我怎样才能解决这个问题 ?

Here is the config/auth.php

这是 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',
    // ],
],

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 授权并继续执行相同的请求。

回答by mfink

Just two updates to restrict your api routes to require your web auth session to make api requests.

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

  1. Update middleware from apito web.
  1. 将中间件从 更新apiweb
# 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. Update middleware from auth:apito auth:web(or simply auth)
  1. 将中间件从auth:apito auth:web(或简单地auth)更新为
# routes/api.php
Route::middleware('auth:web')->get('/user', function (Request $request) {
     return $request->user();
});

回答by Devon

There are quite a few differences between web and api routes in Laravel. The biggest difference being the middleware included by default.

Laravel 中的 web 和 api 路由之间有很多区别。最大的区别是默认包含的中间件。

You can see the differences between the middleware groups in app/Http/Kernel.php:

您可以在 app/Http/Kernel.php 中看到中间件组之间的差异:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],

APIs are supposed to be stateless so cookies and sessions are not set up. Since the api routes do not start the session, you won't have your authenticated session available.

API 应该是无状态的,因此不会设置 cookie 和会话。由于 api 路由不会启动会话,因此您将无法使用经过身份验证的会话。

You could set your routes to use the 'web' group, or see about consuming your own API via Javascript: https://laravel.com/docs/5.6/passport#consuming-your-api-with-javascript.

您可以设置路由以使用“web”组,或者查看通过 Javascript 使用您自己的 API:https: //laravel.com/docs/5.6/passport#sumption-your-api-with-javascript