JWT 多表认证

原因:

一个项目中,举个例子,普通用户和管理后台用户登录,用户分别存在两张表中,需要隔离认证。

实现:

总体就是使用两个中间件去分别认证登录
找到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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!