laravel auth 多表认证

guards修改

修改config/auth.php,在guards中增加所需内容,例如

'guards' => [
    'admin' => [
        'driver' => 'jwt',
        'provider' => 'admins',
    ],

    'user' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],
],

增加auth中相应providers

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

路由中指定走自己的中间件

// 这种写法含义是走名为admin的guard,并且使用auth.admin中间件
Route::group(['middleware' => 'auth.admin:admin'], function () {
    Route::get('admin/changePassword', [AdminIndexController::class, 'changePassword']);
    Route::get('admin/exams', [AdminExamController::class, 'index']);
});

实现自己的AuthAdmin中间件

class AuthAdmin
{
    public function handle(Request $request, Closure $next)
    {
        if (!auth('admin')->check()) {
            return response()->json([
                'code' => 401,
                'msg'  => '登录信息错误',
            ]);
        }

        if (auth('admin')->user()->token != JWTAuth::getToken()) {
            return response()->json([
                'code' => 401,
                'msg'  => '请重新登录',
            ]);
        }

        $request->user = auth('admin')->user();

        return $next($request);
    }
}

此处评论已关闭