laravel 如何在中间件中为路由指定防护?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49525557/
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 17:34:20  来源:igfitidea点击:

How can I specify a guard in middleware for route?

phplaravellaravel-5laravel-middlewarejwt-auth

提问by Maihan Nijat

I have two routes as follow:

我有两条路线如下:

Route::GET('admins/', 'UserController@index')->middleware('jwt.auth');
Route::GET('visitors', 'UserController@indexVisitors')->middleware('jwt.auth');

And I have guards in auth.php:

我在auth.php 中有警卫:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt-auth',
        'provider' => 'users',
    ],
    'visitor_api' => [
        'driver' => 'jwt-auth',
        'provider' => 'visitors',
    ],
],

I tried to specify the guard in the middleware but it doesn't work.

我试图在中间件中指定守卫,但它不起作用。

Route::GET('visitors', 'UserController@indexVisitors')
->middleware('jwt.auth.visitors_api');

回答by aceraven777

I think this is what you want

我想这就是你想要的

Route::GET('visitors', 'UserController@indexVisitors')->middleware('auth:visitors_api');

You can specify a guard by passing it as a parameter (after the colon character)

您可以通过将其作为参数传递(在冒号字符之后)来指定守卫

You can refer to the laravel documentation:

可以参考laravel文档:

https://laravel.com/docs/5.6/authentication

https://laravel.com/docs/5.6/authentication

Under Authentication Quickstart > Protecting Routes > Specifying A Guard

在身份验证快速入门 > 保护路由 > 指定保护下

回答by Amit Shah

If you would like to set a default guard through out the Route::groupthen you can use below syntax

如果您想在整个过程中设置默认防护,Route::group则可以使用以下语法

Route::group(['middleware' => ['web','auth:visitor_api'], 'prefix' => 'visitor'], function() {
  Route::get('/home', 'VisitorController@index')->name('home');
  Route::get('/list', 'VisitorController@list')->name('list'); 
});

after this you can use Auth::id()instead of Auth::guard('visitor_api')->id()in your VisitorController.

在此之后,您可以使用Auth::id()而不是Auth::guard('visitor_api')->id()在您的 VisitorController 中。