首页 > 解决方案 > 如何修复 laravel 中的 JWT 身份验证错误?

问题描述

我正在设计登录 api,当我尝试签入邮递员时,它会引发错误,TypeError:传递给 Tymon\JWTAuth\JWT::fromUser() 的参数 1 必须是 Tymon\JWTAuth\Contracts\JWTSubject 的实例,App 的实例\Models\User 给定,我在 .env 中设置所有警卫、提供者密钥,并且发布也已完成,请帮我解决这个问题。 Error when i am trying to login

 TypeError: Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of App\Models\User given, called in C:\Users\VICKY\Desktop\8\laravel-bookstore\vendor\tymon\jwt-auth\src\JWTAuth.php on line 54 in file C:\Users\VICKY\Desktop\8\laravel-bookstore\vendor\tymon\jwt-auth\src\JWT.php on line 88

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class UserController extends Controller
{
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }
    public function register(Request $request)
    {
        $this->validate($request, [
            'fullName'=>'required|string|between:3,15',
            'emailID'=>'required|email|unique:users',
            'password'=>'required|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/',
            'mobile'=>'required|digits:10'
            ]);
        $user = new User([
            'fullName'=> $request->input('fullName'),
            'emailID'=> $request->input('emailID'),
            'password'=> bcrypt($request->input('password')),
            'mobile'=>$request->input('mobile')           
        ]);
        $user->save();
        return response()->json(['message'=>'Successfully Created user'],201);
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'emailID' => 'required|email',
            'password' => 'required'
        ]);
        $credentials = $request->only('emailID', 'password');
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Invalid Credentials'], 401);
            }
        }catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'],500);
        }
        return response()->json(['token' => $token], 200);
    }
}

User-Model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fullName',
        'emailID',
        'password',
        'mobile'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    /**
     * 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/app.php

'aliases'=>[
 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
        'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class
]

'providers'=>[   Tymon\JWTAuth\Providers\LaravelServiceProvider::class,]

config/auth.php

'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

标签: phplaraveljwt

解决方案


推荐阅读