简体   繁体   中英

How to match input password and database hash password in laravel 8

How to authenticate a user password from a given request in Laravel? How is the password checked against the password hash stored in the database? ** This is my Controller **

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MainController extends Controller
{
    function login1(Request $request){
      $username = $request->input('username');
      $password = $request->input('password');

      

      $data = DB::table('users')->where(['username'=>$username, 'password'=>$password])->first();
      if($data == null){
        echo "error";
    
        $notification = array(
                'message' => 'User Does not Exists!',
                'alert-type' => 'error'
            );
            return back()->with($notification);
      }
else{
    
       
            $request->session()->put('user',$data);
            return redirect('dashboard');
      
      
}
}}

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

if (Auth::attempt($credentials)) {
   // Authentication passed...
}

like this

$encrypted = Crypt::encrypt('password_name_variable');

In basic terms, what you want to do is:

  1. Query the users table for a user, with the given username.
  2. Check whether their hashed password compares the hash of the provided password.

So, you want to first query the table for a user with the given username. Then after retrieving the user, and verifying that they exist , you can then check if the provided password matches the hashed password on the retrieved model.

public function login(Request $request): Response
{
    $user = User::where('username', $request->get('username'));

    if (!$user || !Hash::check($request->get('password'), $user->password)) {
        return back()->with([
            'message' => 'Incorrect username and/or password.',
            'alert-type' => 'error'
        ]);
    }

    $request->session()->put('user', $user);

    return redirect('dashboard');
}

However, there is baked in functionality in Laravel for this, and it's probably simpler to do something like this, depending on your needs:

public function login(Request $request): Response
{
  if (!Auth::attempt(['username' => $request->get('username'), 'password' => $request->get('password')]) {
        return back()->with([
            'message' => 'Incorrect username and/or password.',
            'alert-type' => 'error'
        ]);
    }

    return redirect('dashboard');
}

https://laravel.com/api/8.x/Illuminate/Support/Facades/Auth.html#method_attempt

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