JWT令牌无法生成

时间:2019-07-04 10:59:58

标签: php laravel

我正在尝试在laravel中生成JWT令牌。我正在使用Tymon。我在laravel 5.8中工作,我需要从5.4版本中复制大多数内容。

到目前为止,这是我尝试过的。

控制器

$payload = (object)array("userid" => $user->userid);
$extra = [
      "userid" => $user->userid,
      "username" => $user->username,
      "useremail" => $user->useremail
   ];

$return = JWTAuth::fromUser($payload, $extra);

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];


    protected $hidden = [
        'password', 'remember_token',
    ];


    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

我正在使用邮递员尝试此操作,但出现此错误:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of stdClass given, called in 

2 个答案:

答案 0 :(得分:1)

要在Laravel中使用JWT Auth,您必须遵循以下步骤-

  1. 通过以下方式安装在Composer.json中:

composer require tymon/jwt-auth

  1. 将服务提供者添加到config / app.php配置中的providers数组中 文件如下:
'providers' => [

    ...

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
  1. 运行以下命令以发布程序包配置文件:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

您现在应该拥有一个config / jwt.php文件,该文件可让您配置此软件包的基础。

  1. 通过以下命令生成密钥:
php artisan jwt:secret

这应该使用以下内容更新您的.env文件:

JWT_SECRET=foobar
  1. 然后将用户模型更新为:
<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}
  1. 最后,将config/auth.php中的Auth保护配置为:
'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

然后您就可以出发了。

答案 1 :(得分:0)

如错误消息所述,您正在传递一个stdClass实例,其中JWTSubject实例应作为JWTAuth :: fromUser方法的第一个参数。

看看这个问题:github issue

开发人员建议通过用户模型或Tymon \ JWTAuth \ Contracts \ JWTSubject接口的实现

相关问题