Posted: 21-05-2021

Laravel 8 Password rules

Laravel 8 Password rules

Working on some new features in maguttiCms, I've recently implemented the new Laravel Password rule object in order to ensure that user's passwords have an adequate level of complexity.

 

Basic Implementation

The Password rule object  implements the following methods:

// Require at least 8 characters...
Password::min(8)

// Require at least one letter...
Password::min(8)->letters()

// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()

// Require at least one number...
Password::min(8)->numbers()

// Require at least one symbol...
Password::min(8)->symbols()

Of course, you may chain all the methods in the examples above so you can write a validation rule like this:

Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols();


In addition, you may add an extra layer of security to ensure that a password has not been compromised in a public password data breach leak using the uncompromised method:

Password::min(8)->uncompromised()

Internally, the Password rule object uses the k-Anonymity model to determine if a password has been leaked via the haveibeenpwned.com service without sacrificing the user's privacy or security.

Password::min(8)
    ->letters()
    ->mixedCase()
    ->numbers()
    ->symbols()
    ->uncompromised(3)
// Ensure the password appears less than 3 times in the same data leak...


Use the same password validation rules in different places


In an application usually we use the same password validation rules in different places, so you can find convenient define it in a single place.

You can easily accomplish this using the Password::defaults method, which accepts a closure. The closure given to the defaults method should return the default configuration of the Password rule. Typically, the defaults rule should be called within the boot method of one of your application's service providers:

use Illuminate\Validation\Rules\Password;

/**
 * Bootstrap in your application service provider.
 *
 * @return void
 */
public function boot()
{
    Password::defaults(function () {
        $rule = Password::min(8);

        return $this->app->isProduction()
                    ? $rule->mixedCase()->uncompromised()
                    : $rule;
    });
}

 

You may invoke the defaults method  and re-use the validation rules in this way:

'password' => ['required', Password:defaults()]


Localize the Password validation errors message


By default the Password validation errors message are written in English.

If you need to localize them you may be defined within JSON files that are placed within the resources/lang 

/resources
    /lang
        it.json
        es.json
fr.json


Hereafter an example:
You can find the validation rules translation's in json format  on Laravel Lang package 


For more details about the Password rules see the offical Laravel documentation.