设置路由组的默认保护

时间:2018-03-02 14:52:29

标签: php laravel

我为我的用户设置了一个API令牌,他们可以选择在访问API路由时提供其他数据。

这是我的 auth.php 配置:

'defaults' => [
    'guard' => 'web',      
],    
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'eloquent',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'eloquent',
    ],
],

我的代码中有各种(共享)位置,使用$request->user()之类的检查而不提供防护。问题是这总是使用默认防护。

但是,如果我将其中一条API路由设置为使用中间件auth:api,那么它默认使用api guard,正如我所期望的那样。我无法真正设置它,因为正如我所提到的,身份验证是可选的,使用auth中间件使其成为必需的。

我想知道是否有办法设置所有API路由,使其默认防护是API防护。

4 个答案:

答案 0 :(得分:5)

对我来说,最简单的方法是将以下行添加到Api \ Controller(扩展所有类的那个)中:

public function __construct()
{
    // We set the guard api as default driver
    auth()->setDefaultDriver('api');
}

答案 1 :(得分:3)

经过一番调整之后,我想我已经找到了我认为合理的解决方案:

我创建了以下中间件:

class GuardSwitcher {
    public function handle($request, \Closure $next, $defaultGuard = null) {
        if (in_array($defaultGuard, array_keys(config("auth.guards")))) {
           config(["auth.defaults.guard" => $defaultGuard]);
        }
        return $next($request);
    }
}

然后我将其添加为路由中间件:

 protected $routeMiddleware = [ 
          // ... more
          'guardswitcher' => GuardSwitcher::class
 ];

然后我在Kernel.php中的api中间件堆栈中添加了这个中间件,即:

'api' => [
     'guardswitcher:api',
     // ... more
 ],

在此过程之后,这就是Kernel.php的样子:

class Kernel extends HttpKernel
{
    protected $middleware = [
       //These are the global framework middleware which were not changed
    ];

    protected $middlewareGroups = [
        'web' => [
           //Web middleware, no changes here
        ],

        'api' => [
            'guardswitch:api',
            // Other group middleware
        ]
    ];

    protected $routeMiddleware = [ 
        // Other middleware go here   
        'guardswitch' => DefaultGuardSwitch::class, // This is what's added
    ];
}

答案 2 :(得分:2)

我相信这可以达到相同的结果。

内核

        //...
        'api' => [
        //...
        GuardSwitcher::class
    ],

Guard Switcher中间件

class GuardSwitcher
{

    public function handle($request, Closure $next)
    {
        if (auth()->getDefaultDriver() == 'web') {

            auth()->setDefaultDriver('api');
        }

        return $next($request);
    }
}

现在将为api路由文件或api组中的所有传入请求设置默认驱动程序。

答案 3 :(得分:0)

如果我理解正确,您可以使用Route-Groups

在此示例中,路由组中的所有路由都必须通过auth中间件。

    Route::group( [ 'middleware' => 'auth' ], function(){
        Route::get('/page',  'Controller@function');
    } );
相关问题