【问题标题】:adding more than one middleware to controller in laravel 5.4在 laravel 5.4 中向控制器添加多个中间件
【发布时间】:2017-10-09 07:26:11
【问题描述】:

我有一个功能,我想由两个不同的守卫访问,如果用户或管理员中的任何一个登录,他/她可以访问该功能

如果我这样做,则需要两个人(用户和管理员)都登录才能访问该功能

class HomeController  extends Controller
{
    public function __construct()
        {
            $this->middleware('auth')->only('showABC');
            $this->middleware('auth:hr');
    }
}

但我希望如果登录了两种类型中的任何一种,他/她可以访问 showABC 方法。 我需要使用“OR”而不是“AND”

【问题讨论】:

  • 我可以帮助你。但我需要更多信息:您在哪里写过上面提到的几行?
  • 谢谢,这是在我的控制器中

标签: php laravel authentication


【解决方案1】:

我建议您制作自己的中间件,您可以在其中以默认方法handle 编写您的身份验证代码。然后您只需要调用该中间件即可获得任一用户的身份验证。

app/Http/Middleware/CustomAuthentiation.php 内部制作一个中间件 并在那里写下你的逻辑,就像这样 sn-p:

class CustomAuthentiation
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // Write your authentication code here and then in last lines, if all is good, forward the execution ahead. Like :
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

然后将其添加到 app/Http/Kernel.php 的 Kernel.php 文件中的 $routeMiddleware 数组中,如下所示:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'myAuth' => \App\Http\Middleware\CustomAuthentiation::class  // Here is your middleware..
        ];

然后你可以像这样在routes/web.php 中绑定这个中间件:

Route::middleware('myAuth')->post('login', 'LoginController@LoginUser');

希望这会有所帮助。

【讨论】:

  • 我从你的代码中找到了一种方法,现在我在 eaxch 函数之前检查保护,例如: if (Auth::guard('hr')->check() || Auth::guard('web ')->check()) { //我的函数}
  • 很好,但是您是否在控制器中检查此if 条件?
  • 是的,在我需要两个用户都可以访问的每个功能中
猜你喜欢
  • 1970-01-01
  • 2017-11-28
  • 2020-03-26
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 2015-11-01
  • 2017-12-04
相关资源
最近更新 更多