Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Verify if entered password is compromised in data leak or not in Laravel 8.x

In my previous article, I talked about the new custom password rule object which brings in the ability to easily add various validation rules to the password field.

There are a lot of interesting rules that this object is introducing but the one that really caught my eyes is the password rule that validates if the entered password is exposed in a data leak in the past or not.

Using the uncompromised() rule

First, check how you can add this password rule to your password field.

use Illuminate\Validation\Rules\Password;

$request->validate([
    // Ensures the password has not been compromised in data leaks.
    'password' =>  ['required', 'confirmed', Password::uncompromised()],
]);

As you can tell, you’d need to use the uncompromised() method of the Illuminate\Validation\Rules\Password object which will determine if the entered password is leaked in one of the data leaks in past or not.

If the password has been leaked somewhere, it will give you the following validation message.

That’s pretty neat, right?

Behind the scenes

I tried to dig this feature to know how it all works and found that it is using have i been pwned? API under the hood in Illuminate\Validation\NotPwnedVerifier which checks if the password is previously leaked or not like so.

/**
 * Search by the given hash prefix and returns all occurrences of leaked passwords.
 *
 * @param  string  $hashPrefix
 * @return \Illuminate\Support\Collection
 */
protected function search($hashPrefix)
{
    try {
        $response = $this->factory->withHeaders([
            'Add-Padding' => true,
        ])->get(
            'https://api.pwnedpasswords.com/range/'.$hashPrefix
        );
    } catch (Exception $e) {
        report($e);
    }

    $body = (isset($response) && $response->successful())
        ? $response->body()
        : '';

    return Str::of($body)->trim()->explode("\n")->filter(function ($line) {
        return Str::contains($line, ':');
    });
}
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?