将用户角色添加到 jwt, laravel 5 jwt-auth


Add the user role to the jwt, laravel 5 jwt-auth

我有一个 laravel 5 后端,它在使用 jwt-auth 登录时发送一个 jwt 令牌作为 json 响应。

现在我想将用户角色添加到 laravel发送的 jwt 令牌中,我尝试了以下方法:

这是我当前的控制器

<?php 
namespace App'Http'Controllers;
use Illuminate'Http'Request;
use App'Http'Controllers'Controller;
use JWTAuth;
use Tymon'JWTAuth'Exceptions'JWTException;
use Illuminate'Database'Eloquent'Model;
use App'User;
class AuthenticateController extends Controller
{
    public function authenticate(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only('email', 'password');
        $user = User::where('email', '=', $credentials['email'])->first();
        $customClaims = ['role' => $user->role];
        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials, $customClaims)) {
                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);
        }
        // all good so return the token
        return response()->json(compact('token'));
    }
}
?>

有没有更清洁的方法可以做到这一点?

您当前正在查询用户两次,一次使用电子邮件获取角色,第二次在jwt::attempt()方法中使用。我建议将查询减少到只有一个,但执行身份验证{Auth::try($credientials)},然后将检索到的用户与自定义声明一起传递到JWT::fromUser()方法中。所以

JWT::fromUser($user,['role' => $user->role])

很奇怪,指定一些$customClaims作为 try() 方法的第二个参数实际上对我有用。

但是,您是否尝试过使用JWTFactory外观?它使您可以创建所需的每种令牌。

您可以在此处获取更多信息:JWT-身份验证创建令牌页面。

正如安装指南所建议的那样,在安装 JWT-Auth 时不要忘记将其添加为外观!

希望对您有所帮助!

在当前稳定版本的 JWTAuth[0.5.9] 中似乎没有更干净的方法。

看看以下问题 #89 #108

正如作者在他的评论中指出的那样,他的下一个版本中将涵盖此问题进行改进。你可以看看他的开发分支。

JWT v1.0的文档会引起混乱。
将此方法添加到用户模型,以便在对用户进行身份验证时添加自定义声明:

public function getJWTCustomClaims()
{
        return = [
            'type' => 'driver',
            'id' => $this->driver->id
        ];
}