Bassel.raouf Fakhry
Bassel.raouf Fakhry

Reputation: 1

Laravel 10 JWT authentication - Unable to generate token

I'm currently working with Laravel 10, and I've been trying to implement JWT authentication. However, I've encountered an issue where dd($token) returns false. I've already implemented JWTSubject in my model and updated config\app.php, but I'm still facing this issue. Can anyone provide some assistance?

Here is my controller:

class AuthController extends Controller
{
    use GeneralTraits;
    
    public function login(Request $request) 
    {
        try {
            $rules = [
                "email" => "required | exists:admins,email",
                "password" => "required "
            ];

            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                $code = $this->returnCodeAccordingToInput($validator);
                return $this->returnValidationError($code, $validator);
            }
       
            $credentials = $request->only(['email', 'password']);
            $token = JWTAuth::attempt($credentials);
        
            if(!$token) {
                return $this->returnError(errNum:"E001",msg:"wrong email or password");
            }
      
            $admin = Auth::user();
            $admin->token = $token;
            return $this->returnData(key:"user data", value:$token, msg:"This is user data");

        } catch(\Exception $ex) {
            return $this->returnError($ex->getCode(), $ex->getMessage());
        }
    }
}

I've tried everything I can think of, but I'm still getting the error. Any help would be greatly appreciated.

Upvotes: 0

Views: 214

Answers (1)

darshita_baldha
darshita_baldha

Reputation: 142

$token = auth()->guard('api')->attempt($credentials)

Try authenticating a user using the API guard and the credentials provided in $validator->validated() for creating token.

Upvotes: 0

Related Questions