美文网首页
使用JWTAuth通过user生成jwt-token报错

使用JWTAuth通过user生成jwt-token报错

作者: 如梦又似幻 | 来源:发表于2019-12-02 15:29 被阅读0次

之前使用jwt-auth 0.5版本时,可以使用$token = JWTAuth::fromUser($user);来通过user 来生成jwt-token,现在升级到了1.0版本,发现再使用JWTAuth::fromUser($user)不生效了,而且会报错:
JWT::fromUser() must be an instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of App\Models\User given

jwt报错
打开jwt的源码查看,发现这里有两个方法,
/**
     * Generate a token for a given subject.
     *
     * @param  \Tymon\JWTAuth\Contracts\JWTSubject  $subject
     *
     * @return string
     */
    public function fromSubject(JWTSubject $subject)
    {
        $payload = $this->makePayload($subject);

        return $this->manager->encode($payload)->get();
    }

    /**
     * Alias to generate a token for a given user.
     *
     * @param  \Tymon\JWTAuth\Contracts\JWTSubject  $user
     *
     * @return string
     */
    public function fromUser(JWTSubject $user)
    {
        return $this->fromSubject($user);
    }

这两个方法没看出来有什么区别,应该只是为了兼容之前的老版本而保留。
解决方法就是 修改系统的user model,调用jwt的一个JWTSubject接口,

<?php
namespace Tymon\JWTAuth\Contracts;

interface JWTSubject
{
    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier();

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims();
}

并实现接口中的两个方法:

<?php

namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends authenticatable implements JWTSubject
{
    /**
     * 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 [];
    }
}

相关文章

网友评论

      本文标题:使用JWTAuth通过user生成jwt-token报错

      本文链接:https://www.haomeiwen.com/subject/hvqfgctx.html