ylerjen
ylerjen

Reputation: 4249

Lumen, authentication attempt always returns false (jwt or auth)

I made a small API with the php lumen framework.

Now I'm integrating a jwt authentication (following this tuto http://laravelista.com/json-web-token-authentication-for-lumen/) for my application but as I attempt to login, it always returns false...

It doesn't seem to be a problem with jwt directly because the token generation works but only the login doesn't work. As I saw, jwt use the Lumen Auth:: to login, so to be sure I tried to login with Auth::attempt() directly instead of JWTAuth::attempt, but the result is false too... Here is my code:

try
{
   $validation = $this->validate($request, [
      'email'    => 'required|email',
      'password' => 'required'
   ]);

   $credentials = $request->only('email', 'password');

   $isAuthenticated = Auth::attempt($credentials) || JWTAuth::attempt($credentials);

   $user = User::first();
   $token = JWTAuth::fromUser($user);

   $result = [
     'isAuthenticated' => $isAuthenticated,
     'token' => $token
   ];
 // ... catch exceptions + return $result or errors from exceptions

I made some search to correct the common mistakes with this kind of problems, and I already checked that:

But no changes... I always get a 'false' ! What can be the problem?

Here are the framework version I use (from composer.json)

    "laravel/lumen-framework": "5.1.*",
    "vlucas/phpdotenv": "~1.0",
    "doctrine/dbal": "~2.3",
    "illuminate/mail": "^5.1",
    "tymon/jwt-auth": "^0.5.6",
    "basicit/lumen-vendor-publish": "^1.0",
    "illuminate/support": "5.1.25",
    "illuminate/routing": "5.1.25"

Note : I also notice that for the same password hashed twice, the result is not the same. As I read, it's normal and the Auth knows how to check the hashed stored password. But I don't get it... How does he check the password if the hashed result is never the same? It stores a salt for each hash?

Upvotes: 3

Views: 6315

Answers (1)

ylerjen
ylerjen

Reputation: 4249

Well... Took me a while but I figured out how to login properly...

If I set the password without hashing it :

$user = User::select('id', 'email')
  ->where('email', $email)
  ->first();
$user->password = $newPassword;
$user->save();

and I look in the db what was inserted, the password is stored encrypted...

Then if I try to login with :

$this->validate($request, [
    'email'    => 'required|email|max:255',
    'password' => 'required'
]);
$credentials = $request->only('email', 'password');
if ( $token = JWTAuth::attempt($credentials) )
...

it works properly.

So my problem was that I hashed twice the password before inserting it.

But I don't really understand why it's automatically hashed because as I saw in the doc, I have to do it explicitely. So if anyone can give me the reason, I would be very intersted to know it.

Anyway, I should have used Hash::needsRehash($hashed) directly...

Upvotes: 6

Related Questions