我正在尝试在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);
<?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
答案 0 :(得分:1)
要在Laravel中使用JWT Auth,您必须遵循以下步骤-
composer require tymon/jwt-auth
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
您现在应该拥有一个config / jwt.php文件,该文件可让您配置此软件包的基础。
php artisan jwt:secret
这应该使用以下内容更新您的.env文件:
JWT_SECRET=foobar
<?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 [];
}
}
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接口的实现