Search code examples
laravelauthentication

Can't authenticate user with Laravel Auth::Atempt


I'm struggling myself trying to find the reason but can't. It always falss to "else". I'm using sqliteand this is my code:

public function doLogin(Request $request)
{
    $email          = $request['email'];
    $password       = $request['password'];

    if ( Auth::attempt(['email' => $email, 'password' => $password]) )
        return redirect()->route('home');
    return redirect()->back(); 
}  

route

Route::post('/doLogin',['as' => 'doLogin', 'uses' => 'Auth\LoginController@doLogin']); 

Already printed the variables, the values are exatcly the same as the database.

Possible cause of the problem ?

Testing the Variable Receiving Value (Prints the right values)

$usuario = \App\User::find(1)->pluck('email', 'password');  
return ($usuario);  

Printed Value:

{"teste123":"[email protected]"}

Also, If I try this:

public function doLogin(Request $request)
{
    $email          = $request->input('email');
    $password       = $request->input('password');

    dd($request->all());

}  

I get this:

array:4 [▼
  "_token" => "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
  "email" => "[email protected]"
  "password" => "teste123"
  "action" => null
]  

Is it normal action = null ?


Solution

  • It looks like you're storing your passwords in your database as plaintext, and that seems to be the issue. You should never do this, as if you have a security leak, then the infiltrator could easily have access to all of your users' passwords.

    That also seems to be the issue as to why your Auth::attempt is failing. Auth::attempt goes into SessionGuard.php, which eventually calls validateCredentials from EloquentUserProvider.php. This function hashes the password it is given and checks that against what is in the database. Laravel is expecting your password in the database to be hashed (by default it is bcrypt), so the passwords are not matching. It hashes the plaintext password from the $request so it no longer matches the plaintext in your DB.

    Laravel comes with the command php artisan make:auth. If you use this, then you shouldn't have to do your doLogin function. You can just send the logins along the default route. Then when you're testing, sign up your account through the registration to ensure that it's saved in your database in a hash, instead of plaintext.