【问题标题】:Add the user role to the jwt, laravel 5 jwt-auth给jwt添加用户角色,laravel 5 jwt-auth
【发布时间】:2015-05-14 21:34:41
【问题描述】:

我有一个 laravel 5 后端,它在使用 jwt-auth 登录时将 jwt-token 作为 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 for php 的文档记录不佳。做一个简单的登录/注销系统是痛苦的!看看我的问题。
  • 我也在找同样的东西,你找到解决办法了吗?
  • 我选择了上面的解决方案,即使它是另外一个查询。找不到更清洁的解决方案
  • 您可以根据自己的喜好创建令牌。它不必是用户或一组权限。 github.com/tymondesigns/jwt-auth/wiki/… 所以我认为最好在你的模型或存储库上设置这个登录名并调用它?

标签: php laravel jwt


【解决方案1】:

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

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

【讨论】:

  • 这个链接 auth.readthedocs.io/en/develop/quick-start 解决了我的问题。
【解决方案2】:

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

但是,您是否尝试过使用 JWTFactory 外观?它可以让你创建你想要的每一种令牌。

您可以在此处获取更多信息:JWT-Auth Creating Tokens Page

作为installation guide suggests,不要忘记在安装JWT-Auth时将其添加为Facade!

希望对你有帮助!

【讨论】:

    【解决方案3】:

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

    看看以下问题#89#108

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2016-08-18
        • 2015-09-21
        • 2018-06-26
        • 2020-12-26
        • 2018-10-06
        • 2018-03-30
        • 2017-02-13
        • 2016-07-18
        • 2020-05-11
        相关资源
        最近更新 更多