简体   繁体   中英

validation is not working Laravel custom authentication for bcrypted password

I have created a registration system where password are storing in bycript form. But While I am trying to validate for login purpose, it's saying wrong password. My code for authentication is given bellow:

public function authenticate(Request $request){
    $email=$request->post('email');
    $password=$request->post('password');

    $result=Admin::where(['email'=>$email,'password'=>$password])->get();
    if(isset($result['0']->id)){
        $request->session()->put('ADMIN_LOGIN',true);
        $request->session()->put('ADMIN_ID',$result['0']->id);
        return redirect('admin');
    }else{
        $request->session()->flash('error','Please enter valid login details');
        return redirect('admin-login');
    }
}

You have to find the admin by email like this:

$admin = Admin::where(['email'=>$email])->first();

and than compare the hashes

if ($admin && Hash::check($admin->password, $password)) {
   // ... logged in
} else {
   // ... not legged in
}

You don't need to be building your own authentication system, but this would be the flow:

use App\Models\Admin;
use Hash;

...

public function authenticate(Request $request)
{
    ...

    if ($user = Admin::where($request->only('email'))->first()) {
        if (Hash::check($request->input('password'), $user->password)) {
            // login
        }
    }

    // not authenticated
}

You have to find the user by an identifier, so 'email' is used here. You can't query against the password because it is a hash. If you get a user from the query you can then do a hash check on the submitted password and the user's password from the record.

This is a simplified version of what SessionGuard::attempt / Auth::attempt([...]) is doing.

When your request is processed password comes as plain text while password in your database is hashed. So you have to bcrypt or hash your password first to properly make your query.

You can:

$password = Hash::make($request->post('password'));

Or:

$password = bcrypt($request->post('password'));

Both Hash and bcrypt helper function work in the same way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM