【问题标题】:Laravel middleware authenticationLaravel 中间件认证
【发布时间】:2017-12-30 22:28:42
【问题描述】:

目前要添加身份验证,我在路由文件中使用它:

Route::middleware(['auth'])->group(function () {
});

但如果用户是管理员,我还想检查不同的路由,所以目前我这样做并有一个自定义中间件文件:

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

//

<?php 

namespace App\Http\Middleware;

use Closure;

class Admin {

    public function handle($request, Closure $next)
    {

        if ( Auth::check() && Auth::user()->isAdmin() )
        {
            return $next($request);
        }

        return redirect('dashboard');

    }

}

这一切都很好,但我注意到它使用了 api 中间件:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

问题

  1. 如何制作像 API 一样的命名空间身份验证中间件 'auth:admin'
  2. 设置'auth:api' 中间件的文件在哪里,我在应用文件夹的任何地方都找不到它
  3. 是否还有其他方法可以进行多重身份验证,例如编辑文件 config/auth.php,然后将用户分隔到两个表中,一个用于管理员,另一个用于其他用户。

【问题讨论】:

    标签: php laravel authentication middleware


    【解决方案1】:

    auth:api实际上是基本的auth中间件,以字符串api为参数。这意味着用户是authenticated using the api authentication guard

    如果您为管理员添加了a custom authentication guard,则可以直接使用auth:admin

    【讨论】:

      【解决方案2】:

      auth 中间件接受一个参数,该参数是要使用的守卫。正如您在 Illuminate\Auth\Middleware\Authenticate 中间件中看到的那样。

      您可以添加custom auth guards。因此,您可以根据需要创建auth:admin。但我确实认为使用一个中间件来验证用户是谁(身份验证)和第二个中间件来验证用户是否被允许访问他/她想要访问的页面(授权)是完全可以的。

      【讨论】:

        猜你喜欢
        • 2016-04-27
        • 2021-03-24
        • 2017-06-27
        • 2020-11-09
        • 1970-01-01
        • 2020-07-25
        • 1970-01-01
        • 2020-11-14
        • 2015-04-02
        相关资源
        最近更新 更多