Search by

compertme / laravel-password-policy

CompertMe

Laravel bridge for compertme/password-policy: a NIST SP 800-63B validation rule, config and translations.

Package info

github.com/CompertMe/laravel-password-policy

pkg:composer/compertme/laravel-password-policy

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v1.0.2 2026-12-06 15:57 UTC

This package is auto-updated.

Last update: 2026-12-06 15:58:53 UTC


README

Laravel Password Policy

The Laravel bridge for compertme/password-policy: NIST SP 800-63B rev 4 password checks with your app's config, database, HTTP client and translations.

Tests Packagist version PHP 8.2+ Laravel 12 | 13 License: MIT

Features • Requirements • Setup • Which rule to use • Testing • Reference

A Laravel validation rule, PasswordPolicyRule, that takes the place of Password::default() in your registration, password reset and password update forms. It comes with a guided install, a commented config, a password history table, and a breach check that runs through Laravel's HTTP client.

The checks come from compertme/password-policy and follow NIST SP 800-63B rev 4: length, a blocklist, known breaches, words tied to the user and password history, and no "one uppercase, one digit, one symbol" rules, which NIST asks verifiers not to use.

Features

  • One validation rule for registration, password reset and password update. It reports every problem the checks find; the slow checks (history and the breach check) run only when the quick ones pass.
  • NIST defaults: 15 to 128 characters, no composition rules, and a refusal to run without a blocklist file or the breach check. With bcrypt, Laravel's default hasher, a password is also limited to 72 bytes: 72 ASCII letters, but only 36 Arabic letters.
  • Breach check with Have I Been Pwned through Laravel's HTTP client. Only the first 5 characters of the password's SHA-1 hash are sent, and Http::fake() works in your tests.
  • Password history in a database table, with a trait that saves the old hash when a password changes.
  • User and app words: refuses a password that is the user's name or email, or your app's name or domain. Finding them inside a longer password is an opt-in setting.
  • Everything in the core: leet-speak-aware blocklists (p@ssw0rd counts as password), repeated and sequential passwords (aaaa, 1234), and lengths counted in Unicode characters.
  • Guided setup: password-policy:install asks a few questions and writes a commented config, and password-policy:check loads it and prints what falls short of NIST.
  • Live check route, opt-in and rate-limited, for feedback while the user types.
  • Messages in English and Arabic, and guidelines for AI agents through Laravel Boost.

What the user sees for the password mona, from a user named Mona:

The password must be at least 15 characters long. Spaces at the start or end don't count.

The password is too close to your name, email or other personal details, or to a name tied to this service.

Requirements

  • PHP 8.2 or later
  • Laravel 12, or Laravel 13 with PHP 8.3 or later

Setup

The steps below use the files of Laravel's current starter kits. In another app, make the same changes wherever a password is set.

Note

The rule only checks a new password. It never goes on a login form or a current_password field, so existing users keep signing in with the password they have, and meet the policy the next time they change it.

1. Install the package

composer require compertme/laravel-password-policy
php artisan password-policy:install

password-policy:install asks a few questions, writes config/password-policy.php, and, if you keep password history, publishes its migration. Every setting is explained in the config file itself.

2. Run the migration

Skip this step if you turned password history off.

The published migration adds a password_history table whose user_id is a foreignId on users. If your users have UUID or ULID keys, change foreignId to foreignUuid or foreignUlid first; if your users table has another name, change constrained('users'). Then:

php artisan migrate

3. Prepare the user model

The rule reads the user's words from passwordPolicyWords(), and the trait saves old passwords:

use CompertMe\LaravelPasswordPolicy\HasPasswordHistory;
use CompertMe\LaravelPasswordPolicy\HasPasswordPolicyWords;

class User extends Authenticatable implements HasPasswordPolicyWords
{
    use HasPasswordHistory;

    public function passwordPolicyWords(): array
    {
        return [$this->name, $this->email];
    }
}

4. Use the rule

The starter kits share one passwordRules() method, which has no user. Write the rule in each place instead:

use CompertMe\LaravelPasswordPolicy\PasswordPolicyRule;

// app/Actions/Fortify/CreateNewUser.php, in create(): no user yet,
// so the words come from the form, and [] means no hashes yet.
'password' => ['required', 'string', 'confirmed', PasswordPolicyRule::for([$input['name'] ?? null, $input['email'] ?? null], [])],

// app/Actions/Fortify/ResetUserPassword.php, in reset():
'password' => ['required', 'string', 'confirmed', PasswordPolicyRule::forUser($user)],

// app/Http/Requests/Settings/PasswordUpdateRequest.php, in rules(); keep current_password as it is:
'password' => ['required', 'string', 'confirmed', PasswordPolicyRule::forUser($this->user())],

Then remove the Password::defaults(...) call from AppServiceProvider::boot(). Its uppercase, digit and symbol rules are what NIST asks you not to use, and password-policy:check warns about them while they're there.

5. Save the old password when it changes

Skip this step if you turned password history off.

Important

The package saves nothing on its own. Without this step, the history check only knows each user's current password.

Call rememberPassword() before the new password is stored, in one transaction with the change. In ResetUserPassword::reset():

DB::transaction(function () use ($user, $input) {
    $user->rememberPassword();
    $user->forceFill(['password' => $input['password']])->save();
});

In SecurityController::update() (app/Http/Controllers/Settings/SecurityController.php):

DB::transaction(function () use ($request) {
    $request->user()->rememberPassword();
    $request->user()->update(['password' => $request->password]);
});

Both examples store the password as typed, because the starter kits' User model casts password to hashed. Without that cast, store Hash::make($password) instead.

6. Check the setup

php artisan password-policy:check

It loads your config and blocklists, and prints any setting that falls short of NIST. Then run your test suite, and see Testing.

Which rule to use

Situation Rule
Registration: no user yet PasswordPolicyRule::for([$name, $email], [])
Reset or update, with the history table PasswordPolicyRule::forUser($user)
Reset or update, history on but no table: the current password only PasswordPolicyRule::forUser($user, [$user->getAuthPassword()])
Reset or update, history off PasswordPolicyRule::forUser($user)
No user data at all PasswordPolicyRule::withoutUserData()

for() takes the user's words, then their password hashes, current hash first. forUser() takes the words from passwordPolicyWords(), and the hashes from the history table unless you pass them.

While history is on, the rule needs the hashes: forUser($user) reads them from the table, and fails if the table doesn't exist. withoutUserData() checks no history at all.

Testing

Fake the breach check. It's on by default, so your app's tests would call Have I Been Pwned. In your base TestCase::setUp():

use Illuminate\Support\Facades\Http;

Http::preventStrayRequests();
Http::fake(['api.pwnedpasswords.com/range/*' => Http::response(str_repeat('0', 35).":0\r\n")]);

With that answer, no password counts as breached.

Change the test passwords. The starter kits' tests register and reset with password, which is now refused as too short. Use a value of 15 or more characters that isn't a sequence, such as correct-horse-battery-staple. Change the tests, not the policy.

Reference

Install command

php artisan password-policy:install asks these questions, every one a choice. Nothing is written until the last answer, so stopping halfway changes nothing.

Question Asked when Preselected
config/password-policy.php already exists. Replace it? the config is already published no
Refuse passwords that appeared in known data breaches? always yes
If Have I Been Pwned is down, what happens to the password? allow or reject the breach check is on allow
Hashing driver is custom. Which algorithm does it use? hashing.driver isn't bcrypt, argon or argon2id I don't know
Does your app hash passwords exactly as typed? typed, nfc, unknown always typed
Refuse passwords the user used recently? always yes
How many recent passwords are refused, the current one included? 3, 5, 10 the history table is on 5
Add a route that checks the password while the user types? always no
How many live checks may one IP address send per minute? 15, 30, 60 the live check is on 30
Refuse passwords built from your app's name or domain? app.name or app.url is set yes

Then it runs password-policy:check and exits with its code. With --no-interaction, every question takes its preselected answer.

It stops without writing anything, and exits with 1, when you don't replace an existing config, and when you answer "I don't know" for a custom hashing driver. --no-interaction stops in both cases too. It doesn't ask about blocklist files: with the breach check off, add one in the config.

A custom hashing driver whose algorithm you don't know yet: running the command again asks the same question, so the command tells you to set it up by hand instead: publish the config, set hash_algorithm (or max_bytes), publish the migration if you keep history, and run password-policy:check.

By hand:

php artisan vendor:publish --tag=password-policy-config
php artisan vendor:publish --tag=password-policy-migrations
php artisan vendor:publish --tag=password-policy-translations

A config published this way has hashed_form set to unknown, which tries both forms of each old password. Set it to typed unless your app normalizes passwords before hashing them; the install command writes typed for you.

Config

config/password-policy.php explains every setting in its comments, and the core README's Settings has the full detail.

Important

The policy needs a blocklist file or the breach check: the pattern blocklist alone isn't enough. With the breach check off and no blocklist file, every check throws InvalidConfiguration.

  • Minimum length. Keep min_length at 15. Lower it to 8 only when every login with the password needs a second factor that the user can't turn off.
  • Custom hashing driver. The byte limit follows Laravel's hashing.driver (bcrypt, argon or argon2id). With a custom driver, set hash_algorithm or max_bytes, and the history check uses Laravel's Hash::check(). Why bcrypt limits some users below NIST's 64 characters: Bcrypt and NIST's 64 characters.
  • Breach check outages. With on_unavailable at allow, a password set while Have I Been Pwned is down isn't checked against breaches. reject refuses it instead, and the user tries again later.
  • Typos. An unknown key, at the top level or inside blocklists, breach_check or live_check, or a wrong type, throws InvalidConfiguration naming the key. password-policy:check shows it too.

Password history

rememberPassword() saves the hash being replaced, and keeps history_limit minus one saved hashes per user. With history off, it saves nothing. Deleting a user removes their rows; a soft delete keeps them.

Right after install the table is empty, so only each user's current password is known. Earlier passwords are caught once users change them through code that calls rememberPassword().

The trait also gives passwordHistoryHashes(): the current hash and the saved ones, newest first. Without the trait, use app(PasswordHistory::class)->remember($user) and hashesFor($user).

Live check

A route for feedback while the user types. It runs the quick rules only: length, blocklists and the user's words. It skips history and the breach check.

Warning

Passing the live check is not final. The full check runs when the form is submitted, with PasswordPolicyRule.

Turn it on in config/password-policy.php, with the limit of requests a minute per IP address:

'live_check' => [
    'enabled' => true,
    'per_minute' => 30,
],

The route is POST /password-policy/check (named password-policy.check), on the web middleware group, so send the CSRF token as your forms do, and Accept: application/json. Guests can call it. Send password, and optionally the user's words in words:

{"password": "mona", "words": ["Mona Hassan", "mona@example.com"]}

For a logged-in user, the words from passwordPolicyWords() are added. The answer, with status 200:

{
    "passed": false,
    "violations": [
        {"code": "too_short", "params": {"min": 15}, "message": "The password must be at least 15 characters long. Spaces at the start or end don't count."},
        {"code": "context_word", "params": {}, "message": "The password is too close to your name, email or other personal details, or to a name tied to this service."}
    ]
}

Branch on code, not on message; the codes are listed in the core README's Violation codes. A request without a string password, or with words that aren't a list of strings, gets Laravel's 422 validation answer. A request over the limit gets 429.

With live_check.enabled false, the route doesn't exist. If you cache config and routes, run php artisan config:cache and then php artisan route:cache after turning it on or off.

Check command

php artisan password-policy:check

It builds the policy from your config, loads every blocklist, and prints the policy's diagnostics, such as the byte limit of bcrypt. It also warns when Password::defaults() asks for composition rules. Where that rule is empty, as the starter kits' is outside production, it says so: run the command in production too.

It exits with 1 when the config can't build a policy or a blocklist can't be loaded, and with 0 otherwise, even when it prints diagnostics. To make every diagnostic fail it, set strict_nist to true.

Messages

English and Arabic are included. A locale such as ar_EG uses the ar sentences; a language with no sentences falls back to your fallback locale, then English.

To change a sentence, publish the translations (php artisan vendor:publish --tag=password-policy-translations) and edit vendor/password-policy/<locale>/messages.php in your app's language folder: lang/ in a new app, resources/lang/ in some older ones.

AI agents

The package ships guidelines for Laravel Boost in resources/boost/guidelines/core.blade.php: ten rules for AI agents working in your app, such as saving the old hash on every password change and never asking for composition rules. Boost adds them to your agent files when you run php artisan boost:install or boost:update. Without Boost, password-policy:install says how to install it.

Security

Report a vulnerability as described in the core package's SECURITY.md.

Built by CompertMe

CompertMe

Built and maintained by CompertMe.