DevGe
DevGe

Reputation: 1449

How to fix 401 unauthorized status when logged in using the postman

I have problem regarding to these 401 Unauthorized status, I don't know why it gives that status when I try to test my Authentication login to the postman,

I just watching what the video is doing

Bitfumes JWT Tutorial

This is my table in my database

Sample Table

This my postman:

My Postman

The login function gives me response of error.

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

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

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

Upvotes: 0

Views: 1655

Answers (1)

Rik
Rik

Reputation: 519

Since this question contains multiple errors I'll just write it all up as an answer.

You probably don't have the api guard set up as the default middleware. To fix that, change the middleware (he also does that in the video) which is also described in the documentation (https://jwt-auth.readthedocs.io/en/develop/quick-start/) in the Configure Auth guard part.

If you don't want to change your default guard then just change your attempt method like this: $token = auth()->guard('api')->attempt($credentials);

With your code this will still result in an error because you're defining the token variable inside the if statement. So just define the token outside of the if statement and use it. This is the complete edited version of your code.

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

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

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

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

Upvotes: 1

Related Questions