Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页 [英] Laravel using web authentication in all api routes redirect to home

查看:40
本文介绍了Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对所有 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.

  1. 将中间件从 api 更新为 web.
  1. Update middleware from 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 更新为 auth:web(或简单的 auth)
  1. Update middleware from auth:api to auth:web (or simply auth)

# routes/api.php
Route::middleware('auth:web')->get('/user', function (Request $request) {
     return $request->user();
});

这篇关于Laravel 在所有 api 路由中使用 Web 身份验证重定向到主页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆