【问题标题】:Laravel - How to get the guard that authenticated the user?Laravel - 如何获得对用户进行身份验证的守卫?
【发布时间】:2017-08-06 04:06:03
【问题描述】:

我有一个定制的 LoginController 有两个功能:

loginCustomer 运行 Auth::guard('customer')->attempt(...);

loginEmployee 运行 Auth::guard('employee')->attempt(...);

我在 config.auth 中自定义了两个守卫,指向我的两个模型(客户和员工)并保护后台和前端的路由。

现在在我自定义的 LogoutController 中,我想运行 Auth::logout() 但它不起作用,因为我认为它使用了默认保护。

仅当我指定 Auth::guard('customer')->logout()Auth::guard('employee')->logout() 时才有效,具体取决于用于登录的守卫。

有什么办法可以让守卫用来验证用户身份,所以我只能使用Auth::guard($guard)->logout

【问题讨论】:

    标签: laravel


    【解决方案1】:

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

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

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

    【讨论】:

    • 这不是完美的解决方案,因为它不会返回守卫,但它解决了注销的主要目标
    【解决方案2】:

    你可以使用shouldUse方法:

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

    在你的情况下:

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

    在此之后你可以使用 Auth::logout 并且之前选择的保护(通过shouldUse)将被使用:

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

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

    【讨论】:

    • 我已经尝试过您的解决方案,但它在 LougoutController 中不起作用。但它在登录功能中起作用,所以我在尝试之前添加了 Auth::shouldUse('customer') 并将 Auth::guard('customer')-attempt(...) 更改为 Auth::attempt(...)
    • 我进行了额外的测试并意识到您的解决方案通过将注销功能从 LogoutController 移动到 LoginController 来工作。
    • 我很高兴听到这个消息。
    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 2021-05-01
    • 2018-05-12
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2016-09-26
    相关资源
    最近更新 更多