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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29014681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:08:00  来源:igfitidea点击:

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

phplaraveljwt

提问by RVandersteen

I have a laravel 5 backend that sends an jwt-token as a json response on login with jwt-auth.

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

Now I would like to add the user role to the jwt token that laravel sends, I tried the following way:

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

This is my current controller

这是我当前的控制器

<?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'));
    }
}
?>

Is there a cleaner way to do this ?

有没有更干净的方法来做到这一点?

采纳答案by Olatunde Alex-Oni

You are currently querying for the user twice, once using the email for the purpose of getting the role and the second within the jwt::attempt()method.I would suggest reducing the queries to just one but doing the authentication {Auth::attempt($credientials)} and then passing the retrieved user into JWT::fromUser()method, along with the custom claim. so

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

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

回答by Francesco Malatesta

It's strange, specifying some $customClaimsas second parameter for the attempt()method actually works for me.

奇怪的是,将一些$customClaims指定为attempt()方法的第二个参数实际上对我有用

However, have you tried to use the JWTFactoryFacade? It lets you create every kind of token you want.

但是,您是否尝试过使用JWTFactoryFacade?它可以让你创建你想要的各种令牌。

You can get more info here: JWT-Auth Creating Tokens Page.

您可以在此处获取更多信息:JWT-Auth 创建令牌页面

As the installation guide suggests, don't forget to add it as a Facade while installing JWT-Auth!

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

Hope it helps!

希望能帮助到你!

回答by Lithium

It seems that there isn't a cleaner way in the current stable version of JWTAuth[0.5.9].

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

Take a look on the following issues #89#108

看看下面的问题#89 #108

As the author pointed out in his comments there will be improvements in his next release covering this issue. You can take a look on his develop branch.

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

回答by Cyber

JWT v1.0's documentation causes confusion.
Add this method to your user model, so you can add custom claims when you authenticate users:

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

public function getJWTCustomClaims()
{

        return = [
            'type' => 'driver',
            'id' => $this->driver->id
        ];
}