Laravel 9 tymon/jwt-auth错误“无效凭据”登录时使用用户名而不是电子邮件

lawou6xi  于 2023-03-13  发布在  其他
关注(0)|答案(2)|浏览(233)

当我用用户名和密码字段在Postman上测试我的登录功能时,它总是得到错误消息“无效凭据”。
我试过修改$credentials变量定义,并搜索论坛,没有任何效果。我没有修改任何原始文件从tymon/jwt-auth,任何东西像改变电子邮件到用户名。对于JWT的版本,我使用tymon/jwt-auth:“dev-develop”。
这是我的用户控制器. php

public function login(Request $request)
    {
        // I changed variable definition from $request->only('email', 'password') to $request->only('username', 'password')
        $credentials = $request->only('username', 'password');

        // variable below have the same results
        // $credentials = ['username' => $request->input('username'), 'password' => $request->input('password')];

        try {
            if(! $token = JWTAuth::attempt($credentials)) {
                // Keep getting this error
                return response()->json(['error' => 'invalid credentials'], 400);
            }
        }
        catch (JWTException $e) {
            return response()->json(['error' => 'could not create token'], 500);
        }

        return  $this->createNewToken($token);
    }

这是我的模型User.php

class User extends Model
{
    use HasFactory;
    protected $table='users';
    protected $primaryKey='id_user';
    public $timestamps=false;
    /**
     * fillable
     * 
     * @var array
     */
    protected $fillable = [
        'nama_user', 'role', 'username', 'password'
    ];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }
djmepvbi

djmepvbi1#

用户模型应扩展可验证

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 [];
    }
}
iyfjxgzm

iyfjxgzm2#

这对我有用
https://jwt-auth.readthedocs.io/en/develop/quick-start/

public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

相关问题