JWT 多表認證

CLSun發表於2020-07-28
原因:

一個專案中,舉個例子,普通使用者和管理後臺使用者登入,使用者分別存在兩張表中,需要隔離認證。

實現:

總體就是使用兩個中介軟體去分別認證登入
找到config/auth.php檔案,增加一個providers 和 guards,如下:

'guards' => [
        ......
        'operation_admin' => [
            'driver' => 'jwt',
            'provider' => 'op_admin',
        ],
    ],
    'providers' => [
        ......
        'op_admin'  => [
            'driver' => 'eloquent',
            'model' => App\Models\Operation\AdminModel::class,
        ],
    ],

編寫中介軟體:

class OperateAuth extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->authenticate($request);

        $response = $next($request);

        // Send the refreshed token back to the client.
        return $this->setAuthenticationHeader($response);
    }

    public function authenticate(Request $request)
    {
        $this->checkForToken($request);
        try {
            if (! auth('operation_admin')->user()) {
                throw new UnauthorizedHttpException('jwt-auth', 'User not found');
            }
        } catch (JWTException $e) {
            throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
        }
    }

}

註冊中介軟體:

protected $routeMiddleware = [
        ......
        'operate.renew' => \App\Http\Middleware\OperateAuth::class,
    ];

在route驗證的時候,使用該中介軟體進行驗證:


$api_router = app('Dingo\Api\Routing\Router');
$api_router->group([
    ......
], function ($api) {
    $api->group([
        ......
        'middleware' => [
            'serializer:array',
            'operate.renew',
        ]
    ],function ($api){
      ......
});

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章