Search code examples
laravellaravel-5laravel-5.5laravel-5.6

Laravel 5.6 - Reset Password Tokens how to ensure they match?


When a user forgets their password and try to reset it, they get a reset password email link with a token:

site.com/my/password/reset/ddc3669ab1bbd78abe620ef910716ae91678bb4beb5cd8896e21efaaa0c9d5c6

On the backend though, the token in the database password_resets table looks like it's hashed: $2y$10$O6pgU21FhsOcgpgeqR8RReFYoCGhHNBH5bHKxtE6q1tJMTUufrbr.

So when the route is visited, the only piece of identifying information passed is the token: ddc3669ab1bbd78abe620ef910716ae91678bb4beb5cd8896e21efaaa0c9d5c6

// Controller Method
passwordResetVerifyByToken($token){
  $record = DB::table('password_resets')->where('token', $token)
                                        ->first();
}

Ofcourse we won't get a record, as the plain token from the email will NOT match the hashed one in the database with the above query. So with the plain emailed token link, when the user clicks it, how can we compare it to the one in the database to verify it exists and is a matching token?


Solution

  • You should use the Hash::check method, which will return true or false depending of if the hash of the reset token matches the stored database value.

    if (Hash::check($token, $row->token)) {
        // The passwords match...
    }
    

    Laravel docs: https://laravel.com/docs/5.6/hashing#basic-usage