将用户属性添加到Laravel护照令牌

时间:2018-06-08 23:00:12

标签: laravel laravel-5 jwt laravel-5.6 laravel-passport

您好我想在使用Laravel passport生成的访问令牌中添加一些额外的属性。我正在使用Laravel 5.6

解码后的令牌示例:

aud:"1"
exp:1528505818
iat:1528498618
jti:"10c880c491ecb73e39a6b1d7614b4be4e13ef4adf71fbc6f858a69899461fecc001fdefb60a287c1"
nbf:1528498618
scopes:[]
sub:"1"
user: {
  name: "test"
  role: "admin
}

我已阅读其他文章,但他们只将用户对象附加到响应中,而不是将其编码在令牌中。

或者,如何将角色添加到范围数组?

尝试了以下但没有运气:(500错误:试图获得非对象的属性)

<?php
namespace App\Http\Controllers\API\Auth;

use App\Models\User;
use App\Http\Controllers\Controller;
use Auth;
use Response;

class LoginController extends Controller
{
    public function login() { 
        $content = [];
        if(Auth::attempt(['email' => request('username'), 'password' => request('password')])){
            $user = Auth::user();
            $role = $user->roles()->first()->name;
            $content['access_token'] = $user->createToken('HiveMan App')->accessToken;
            $status = 200;
        }
        else{
            $content['error'] = "Unauthorised";
            $content['message'] = "Your email or password are incorrect";
            $status = 401;
        }
        return response()->json($content, $status); 
    }
}

0 个答案:

没有答案