LoginSignup
0
0

laravelで過去漏洩パスワードのバリデーションをかける

Posted at

【前置き】
PwnedPasswordsというらしいですが、過去漏洩した記録を基に
入力した新しいパスワードを辞書索引し、
一致したらバリデーションとしてエラーを返し再入力を求めるというもの。
使っているLaravelのバージョンは6。

参考にした記事Laravel de パスワードチェッカーではAPIで最新のデータと照合かけるみたいですが、なぜかあんまり精度が高くなく、Pwned Passwords Validator for Laravelも同じく精度が低くセキュリティ的に通らなさそうなんでテストされるとわかってるjsonデータを元に対応。

独自バリデーションルールをつくる

cmd
> php artisan make:rule SafePassword
app\Rules\SafePassword.php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class SafePassword implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}

pwnedPass json読みこんで、パスワードと一致したらfalseを返す

jsonはpublicの/json/に配置した。

app\Rules\SafePassword.phpのpasses()の中
        $json_path = public_path()."/json/PwnedPasswords.json";
        $json = file_get_contents($json_path);
        $json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
        $json = json_decode($json, true);

        if (in_array($value, $json)) {
          return false;
        }
        return true;
app\http\Controllers/ChangePasswordController.phpのvalidator()の中
    return Validator::make($data,[
            'new_password' => ['required', 'confirmed', 'min:8','max:72', new SafePassword]
        ]);
    }
PwnedPasswords.json
    [
        "123456",
    	"123456789",
    	"qwerty",
    ]

jsonは多すぎるから割愛
https://www.ncsc.gov.uk/static-assets/documents/PwnedPasswordsTop100k.txt

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0