tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.3k stars 1.54k forks source link

I get always "Invalid Credentials" #341

Closed r0bin51 closed 6 years ago

r0bin51 commented 8 years ago

Hello. I'm having some issues with my laravel api server using JWT. First of all: I already implemented the same api server and I remember it worked fine. in this moment it doesn't (I made the old version some months ago). Basically, I need to implement a register/login functionalities, and the code is the same that worked months ago (it's the common basic-example code for authentication with jwt)

try { if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'invalid_credentials'], 401); }

the result I get is ALWAYS invalid credentials. the registration works fine, the DB contains the user, but I can't understand why always the same error...

I already checked: - filesystem permissions - database permissions - source code of my routes/controllers files Thank you

dukejib commented 8 years ago

try to check if the passwords are hashed or not? Also, are you using same model for authentication or not.

r0bin51 commented 8 years ago

the pwd are hashed (and the user created) in this way:

else if ($validation->passes()){
$newuser['email'] = $email; $newuser['username'] = $username; $password=Hash::make('password'); $newuser['password'] = $password; return User::create($newuser);

the login is this: $credentials = $request->only(['email', 'username', 'password']);

    $validator = Validator::make($credentials, [
        'email' => 'required_without:username',
        'username' => 'required_without:email',
        'password' => 'required',
    ]);
    if ( $validator->fails() ) {

return response()->json($validator->errors()->getMessages(), 400);
}

    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);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
r0bin51 commented 8 years ago

update: this is my app/User.php ... i read online that the problem could be here

<?php

namespace App;

use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['first_name', 'last_name', 'username', 'email', 'password'];
/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password'];

}

r0bin51 commented 8 years ago

return User::create(['email' => $email, 'password' => bcrypt($password)]);

with this row it works correctly. (null username)

return User::create(['email' => $email, 'password' => bcrypt($password), 'username' => $username]);

in this way , it works but with null username (and i cannot understand why)

$newuser['email'] = $email; $newuser['username'] = $username; $password=Hash::make('password'); $newuser['password'] = $password; return User::create($newuser);

finally in this way it saves the user correctly but the login doest not work...

edit: Solved, it works with $password = bcrypt($password);

joshbodine21 commented 8 years ago

This same issue is happening to me using the code in the documentation.

jadjoubran commented 8 years ago

@joshbodine21 are you doing auth against your App\User model?

joniham commented 8 years ago

I am having this same problem with my new laravel 5.2 installation (jwt-auth 0.5.6).

My users table (in postgresql) is located at: database.schema.members and registering users are working just fine and they appear in DB with hashed passwords. But logging in does not seem to work.

However if i change my app to use database.users the register and login are working just fine.

Could not get it to work with bcrypt neither...

Any ideas?

rawbknalb commented 8 years ago

anything new with this issue? i get the same problem

rapidtechsolutions commented 8 years ago

Same issue here.

jonihlp commented 8 years ago

Actually this issue is not (not in my case anyway) related to jwt-auth. The "issue" is with laravel and its built in auth functionality.

To resolve this i had to define the NAME of password field in my User model:

public function getAuthPassword() { return $this->pwdfield_name; }

And in my AuthController i have to use: JWTAuth::attempt(["usrname_field"=>$request->user, "password" => $request->pass])

So this being said the key is that the "key" of the password field in credientals array MUST be named to "password"...

... this is how i got it working anyway...

Yanniyiyi commented 8 years ago

It works fine with Laravel 5.3. My problem is that my post request does not contain 'email' attribute. So maybe you can check your post request to see if there were 'email' and 'password' attribute

Pedneri1 commented 7 years ago

Solved it by creating my users with the password hashed with Laravel's Hash::make function

ntja commented 7 years ago

Check the length of your password field in DB. Maybe it is truncated

Shirjeel313 commented 7 years ago

Solution...

If your code is correct, then also if your getting output: { "error": "invalid_credentials" }

Just Follow this Steps:---------------

first step check:

dd($request->only('email', 'password')); or dd($credentials); // output should be like this..

array:2 [ "email" => "myemail@myemail.com" "password" => "test123" ]

second step check:

dd($token); // output should be:

false

Last Step Goto: App\Config\auth.php

On line number: 70 Change Model Location where your saved model(User) for example: App\Model\Myuser\User

and

On line number: 71 Change Table Name to what you have set in your model(User) for example: protected $table = 'my_user';

_'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\Myuser\User::class, 'table' => 'myuser' ],

Happy to help you....

deathkillz commented 7 years ago

watch out with postman?

with postman: | POST | http://myapp/api/authenticate | | key -> email | val -> myemail@domain.tld | | key -> password | val -> password |

array (size=2) 'email' => null 'password' => null

with curl: $ curl --request POST 'http://myapp/api/authenticate' --data "email=myemail@domain.tld" --data "password=password"

array (size=2) 'email' => myemail@domain.tld 'password' => password

so beware..

rw3iss commented 7 years ago

To solve this I just had to encrypt the created user's password, ie. within the signup() controller call:

$userData = $request->only('name', 'email', 'password');
// Do validation, etc.
$userData['password'] = bcrypt($userData['password']);
User::unguard();
$user = User::create($userData);
User::reguard();
AlanRezende commented 7 years ago

When I create my users using Hash:make it all works fine. Nothing else to do!

hemant-brb commented 7 years ago

@App\User add a method to set password

public function setPasswordAttribute($value) {
    $this->attributes['password'] = Hash::make($value);
}

@AuthController public function authenticate(Request $request) { $user = new User($request->all()); $user->password = $request->get('password'); //this will call the setPasswordAttribute method of User class $user->save();

    $credentials = $request->only('email', '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(compact('token'));
}

It will work fine :)

ugd commented 3 years ago

What can i do if i would like to change the email column to something else?

farzadj248 commented 7 months ago

This problem has occurred to me several times And the problem was solved only when the hashed password was stored in the database through Laravel itself