我正在使用 Laravel Breeze 开发一个应用程序。当我尝试创建不安全的密码(已泄露/破解的密码,例如
Password1!
)时,我收到此验证错误消息:
给定的密码出现在数据泄露中。请选择不同的密码。
从我的角度来看,这个消息非常简单,但从最终用户的角度来看,恐怕不太清楚。事实上,阅读此消息的最终用户可能想知道我正在处理的网站上的数据是否已泄露,并且感觉所访问的网站不安全,而实际上这提供了额外的安全性。这就是为什么我想自定义我的消息,如下所示:
给定的密码是网络上某个时刻泄露的一部分。作为安全措施,我们已阻止其在本网站上的使用。
技术:
到目前为止我在 RegisteredUserController 中尝试过的内容
public function store(Request $request): RedirectResponse
{
$rules = [
[other rules],
'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->letters()->numbers()->symbols()->uncompromised()],
];
$messages = [
'password.uncompromised' => 'The given password was part of a leak at some point on the Web. As a security measure, we have blocked its use on this site.',
];
$this->validate($request, $rules, $messages);
Auth::login($user = User::create([
[other stuff]
'password' => Hash::make($request->password),
]));
event(new Registered($user));
Auth::login($user);
(new MyController)->store($request);
return redirect()->route('register_step_2');
}
当我使用上面的代码时会发生什么
当我使用上面提供的代码时,默认错误消息是传递到用户界面的消息,而不是我的自定义消息。
这似乎不仅适用于
uncompromised()
,而且适用于自定义规则对象的所有其余内置方法(在Password.php中使用),并且文档根本不涵盖这种情况。
到目前为止,我发现这些内置方法的唯一解决方法是运行
php artisan lang:publish
。然后,您将看到一个 lang/ 目录添加到应用程序的根目录中,您可以在其中找到 validation.php 文件的关联数组中的键,并将其值更改为您想要的任何值:
这是我在 RegisteredUserController.php 中使用的一小段代码:
public function store(Request $request): RedirectResponse
{
$messages = [
// For non built-in methods, this works as mentioned in the documentation
'name.required' => 'We need your name',
];
$rules = [
'name' => ['required', 'string'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Password::min(5)->uncompromised()]
];
$request->validate($rules, $messages);
// The rest of code
}
这是上述代码和更改的结果: