Laravel - 如何获取认证用户的保护器?

7
我有一个自定义的LoginController,其中包含两个函数: loginCustomer,运行Auth :: guard('customer') -> attempt(...); loginEmployee,运行Auth :: guard('employee') -> attempt(...);
我在config.auth中自定义了两个guard,指向我的两个模型(Customer和Employee),并保护后台和前端的路由。
现在,在我的自定义LogoutController中,我想运行Auth :: logout(),但它不起作用,因为我认为它使用了默认guard���
只有当我指定Auth :: guard('customer') -> logout()或Auth :: guard('employee') -> logout()时,它才能正常工作,具体取决于已用于登录的guard。
是否有任何方法可以获取用于验证用户的guard,以便我可以仅使用Auth :: guard($ guard) -> logout?
2个回答

8

这可能不是最完美的解决方案,但它可行。基本上,只需浏览所有守卫,并检查用户是否已通过该守卫进行了身份验证。如果是-注销他。请注意,这将使他从所有已登录的警卫中注销。

此代码将转到您的注销控制器:

  $guards = array_keys(config('auth.guards'));
  foreach ($guards as $guard) {
    if(Auth::guard($guard)->check()) Auth::guard($guard)->logout();
  }

这并不是完美的解决方案,因为它没有返回守卫,但它解决了主要目标,即注销。 - Ricardo Carvalho

8

您可以使用shouldUse方法:

调用此方法后,您可以通过之前设置的守卫注销用户。

在您的情况下:

if( Auth::guard('customer')->attempt(...) ){
    Auth::shouldUse('customer');
}


if( Auth::guard('employee')->attempt(...) ){
    Auth::shouldUse('employee');
}

接下来,您可以使用 Auth::logout,并且之前选择的 guard(通过 shouldUse)将被使用:

// just use Auth::logout without Auth::guard(GUARDNAME)->logout()
Auth::logout();

这个方法的简短文档:https://laravel.com/api/5.4/Illuminate/Auth/AuthManager.html#method_shouldUse

该方法用于检查应该使用哪个用户身份验证驱动程序。如果没有指定,则默认使用config/auth.php文件中的默认驱动程序。

我尝试了你的解决方法,但它在LougoutController中没有起作用。但是在登录函数中它工作正常,所以我在尝试之前添加了Auth::shouldUse('customer')并将Auth::guard('customer')-attempt(...)更改为Auth::atempt(...)。 - Ricardo Carvalho
我做了额外的测试,发现您的解决方案通过将注销函数从LogoutController移动到LoginController中实现。 - Ricardo Carvalho
我很高兴听到这个。 - Alexander Reznikov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接