多用户模型Laravel JWT Auth

时间:2016-04-25 11:23:33

标签: php laravel jwt

我必须在我的口才中使用模型:

  • 用户
  • OfficeUser

OfficeUser在JWT配置中定义为标准模型。 现在我已经编写了一个中间件来验证每个中间件

authUser:

public function handle($request, Closure $next)
{
    Config::set('auth.providers.users.model', \App\User::class);
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

    return $next($request);
}

authOfficeUser

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

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

    return $next($request);
}

此外,我有一个登录功能:

LoginUser

if ($user){
        if (Hash::check($request->password, $user->password)) {
            // grab credentials from the request
            $credentials = $request->only('email', 'password');

            try {
                // attempt to verify the credentials and create a token for the user
                Config::set('auth.providers.users.model', \App\User::class);
                if (! $token = JWTAuth::attempt($credentials)) {
                    return response()->json(['error' => 'invalid_credentials'], 401);
                }
            } catch (JWTException $e) {
                // something went wrong whilst attempting to encode the token
                return response()->json(['error' => 'could_not_create_token'], 500);
            }

LoginOfficeUser

if ($user){
        if (Hash::check($request->password, $user->password)) {
            // grab credentials from the request
            $credentials = $request->only('email', 'password');

            try {
                // attempt to verify the credentials and create a token for the user
                Config::set('auth.providers.users.model', \App\OfficeUser::class);
                if (! $token = JWTAuth::attempt($credentials)) {
                    return response()->json(['error' => 'invalid_credentials'], 401);
                }
            } catch (JWTException $e) {
                // something went wrong whilst attempting to encode the token
                return response()->json(['error' => 'could_not_create_token'], 500);
            }

不幸的是,当我登录并尝试调用authUser中间件后面的路由时,我得到一个" user_not_found"

有人知道为什么会这样吗? OfficeUser身份验证工作正常

2 个答案:

答案 0 :(得分:5)

发现此问题的任何人发布

虽然不建议有两个用户表,但我有一个与我们的客户之一设置JWT的类似要求。这就是我解决问题的方法。

无需对`config / auth.php'中的提供者进行任何更改

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

]

在您的身份验证控制器中,通过设置

动态修改提供者使用的模型

\Config::set('auth.providers.users.model', \App\Trainer::class);

示例代码

在authenticate()方法中

if ($credentials['user_type'] == 'consultant') {

\Config::set('auth.providers.users.model', \App\Trainer::class);

} else {
    \Config::set('auth.providers.users.model', \App\User::class);
}

//Find the user

//Create the token
if ($user) {
   $customClaims = ['user_type' => $credentials['user_type']];
   $token = JWTAuth::fromUser($user,$customClaims);
} else {
  return response()->json(['error' => 'invalid_credentials'], 401);
}

在解析令牌时,您必须执行相同操作以对用户进行身份验证。示例代码

在getAuthenticatedUser()方法中

$payload = JWTAuth::parseToken()->getPayload();
$user_type = $payload->get('user_type');

if($user_type === 'consultant'){
   \Config::set('auth.providers.users.model', \App\Trainer::class);
}else{
   \Config::set('auth.providers.users.model', \App\User::class);
}

if (!$user = JWTAuth::parseToken()->authenticate()) {
    return response()->json(['user_not_found'], 404);
}

答案 1 :(得分:0)

您可以如下更改每个控制器中的__construct功能。这样jwt知道要验证哪种模型。

OfficeUserController

function __construct()
{
    Config::set('jwt.user', OfficeUser::class);
    Config::set('auth.providers', ['users' => [
            'driver' => 'eloquent',
            'model' => OfficeUser::class,
        ]]);
}