简体   繁体   English

如何使用防护作为中间件在LARAVEL中对用户进行身份验证

[英]How to use a guard as an Middleware for authenticating users in LARAVEL

I'm trying to build a webapp that have multiple roles so the one is admin which has a guard named "admin" I can authenticate fine but I just want to protect my routes so other can access it. 我正在尝试构建一个具有多个角色的webapp,因此一个管理员是admin,它的保护名为“ admin”,我可以通过身份验证,但是我只想保护自己的路由,以便其他人可以访问它。

/ How i authenticate my admin / /我如何验证我的管理员/

if (Auth::guard('admin')->attempt(['username' => $username, 'password' => $password])) {

    // if passed
    // redirect to dancedrick media welcome dasboard page
    return ['redirect' => route('cmswelcome')];

   } else {

    // if faills
    // redirect to dancedrick media welcome dasboard page
     return ['redirect' => route('cmsregister')];
   }

I want protect this rountes 我要保护这个人

Route::prefix('admin')->group(function () {

   // redirect admin to cms welcome 
    Route::get('/cms/welcome', [
        'uses' => 'AdminController@cmswelcome',
        'as' => 'cmswelcome',
    ]);

});

Just like using 'middleware' => 'auth' 就像使用'middleware'=>'auth'

You can pass the guard to the admin middleware: 您可以将防护传递给admin中间件:

From the docs : 文档

When attaching the auth middleware to a route, you may also specify which guard should be used to authenticate the user. 将auth中间件附加到路由时,您还可以指定应使用哪个防护对用户进行身份验证。 The guard specified should correspond to one of the keys in the guards array of your auth.php configuration file: 指定的防护应与auth.php配置文件的防护数组中的键之一相对应:

public function __construct()
{
    $this->middleware('auth:api');
}

In your case: 在您的情况下:

Route::prefix('admin')->group(['middleware' => ['auth:admin']],function () {

   // redirect admin to cms welcome 
    Route::get('/cms/welcome', [
        'uses' => 'AdminController@cmswelcome',
        'as' => 'cmswelcome',
    ]);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM