jwt-auth icon indicating copy to clipboard operation
jwt-auth copied to clipboard

the respond Always 401 "Unauthorized"

Open baderAmmoun opened this issue 6 years ago • 13 comments

Subject of the issue

Describe your issue here.

I followed all the configuration in the documentation but always I get the same respond from the server even I send a valid credentials

baderAmmoun avatar Jan 21 '19 16:01 baderAmmoun

Give us more information about your issue. How do you make the call, how does your controller look like, etc. What you described here is not enough to help you with anything.

LastxTemplar avatar Jan 22 '19 10:01 LastxTemplar

my call on the postman : http://127.0.0.1:8000/auth/login the body is: { "email":"[email protected]", "password":"1234" } the rout as following: Route::group([

'middleware' => 'api',
'prefix' => 'auth'

], function ($router) {

Route::post('login', 'AuthController@login');
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::post('me', 'AuthController@me');

});

and the controller :

class AuthController extends Controller {

public function __construct()
{
    $this->middleware('auth:api', ['except' => ['login']]);
}

/**
 * Get a JWT via given credentials.
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function login()
{
    $credentials = request(['email', 'password']);

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

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

/**
 * Get the authenticated User.
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function me()
{
    return response()->json(auth()->user());
}

/**
 * Log the user out (Invalidate the token).
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function logout()
{
    auth()->logout();

    return response()->json(['message' => 'Successfully logged out']);
}

/**
 * Refresh a token.
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function refresh()
{
    return $this->respondWithToken(auth()->refresh());
}

/**
 * Get the token array structure.
 *
 * @param  string $token
 *
 * @return \Illuminate\Http\JsonResponse
 */
protected function respondWithToken($token)
{
    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60
    ]);
}

}

and I implement JWTSubject interface on user model

baderAmmoun avatar Jan 22 '19 11:01 baderAmmoun

Try to change your login function to use guard() instead of auth(). I had a lot of trouble making this work, but in the end, this solution worked for me:

if (! $token = $this->guard()->attempt($credentials)) {
    return response()->json(['errors' => 'These credentials do not match our records.'], 401);
}

LastxTemplar avatar Jan 22 '19 11:01 LastxTemplar

If that works, change all instances of auth() to $this->guard() in your code.

LastxTemplar avatar Jan 22 '19 11:01 LastxTemplar

I tried like this but the method does not exist

baderAmmoun avatar Jan 22 '19 19:01 baderAmmoun

I''m thinking that the problem with hashing password But I don''t know how can I fix it

baderAmmoun avatar Jan 22 '19 19:01 baderAmmoun

Hi, all about this are not a problem with password hashing or guard or also token. It's about EXCEPTION ERROR HANDLER : You must put this in your laravel hander.php exception :

StudiosKelemy avatar Apr 13 '19 19:04 StudiosKelemy

// exception for UnauthorizedHttpException if ($exception instanceof UnauthorizedHttpException) { return response()->json([ "error" => "not authorized" ], 401); }

    // exception for TokenBlacklistedException
    if ($exception instanceof TokenBlacklistedException) {
        return response()->json([
            "error" => "token blacklisted"
        ], 401);
    }

StudiosKelemy avatar Apr 13 '19 19:04 StudiosKelemy

Try and take a look at my repo. I have successfully created a Test driven development environment with laravel 5.8 and jwt. Try and take a look inside app/User.php and app/AuthController.php and other related things. https://github.com/commentatorboy/testttdlaravel/commit/69aad299eac458a873e04d56a18a399e8a85992e

I can say that I DID NOT use the solutions mentioned in this issue.

commentatorboy avatar Apr 20 '19 07:04 commentatorboy

just converter format password

ex 'password' => bcrypt($request->password),

imjad avatar May 14 '20 15:05 imjad

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

stale[bot] avatar Dec 25 '20 17:12 stale[bot]

What occured to me, was solved by @imjad answer,

Actually, the solution of the problem is that the auth() method expects encrypted passwords to be saved in your database. So, save yours passwords like this: bcrypt($request->password).

mateusberlitz avatar Mar 23 '21 18:03 mateusberlitz

if you use postman just change Content-Type: application/json to Content-Type: application/x-www-form-urlencoded

Abdumalik2022 avatar Apr 03 '22 04:04 Abdumalik2022