跳到内容

PasswordStrength

编辑此页

验证给定的密码是否已达到约束要求的最低强度。密码的强度不是通过一组预定义的规则(包括数字、使用小写和大写字符等)来评估的,而是通过测量密码的熵(基于其长度和使用的唯一字符数)来评估的。

基本用法

以下约束确保 User 类的 rawPassword 属性达到约束要求的最低强度。默认情况下,最低要求的分数是 2

1
2
3
4
5
6
7
8
9
10
// src/Entity/User.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    #[Assert\PasswordStrength]
    protected $rawPassword;
}

可用选项

minScore

类型: integer 默认值: PasswordStrength::STRENGTH_MEDIUM (2)

密码的最低强度要求。可用常量为

  • PasswordStrength::STRENGTH_WEAK = 1
  • PasswordStrength::STRENGTH_MEDIUM = 2
  • PasswordStrength::STRENGTH_STRONG = 3
  • PasswordStrength::STRENGTH_VERY_STRONG = 4

PasswordStrength::STRENGTH_VERY_WEAK 可用,但仅在内部或由自定义密码强度评估器使用。

1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/User.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    #[Assert\PasswordStrength([
        'minScore' => PasswordStrength::STRENGTH_VERY_STRONG, // Very strong password required
    ])]
    protected $rawPassword;
}

message

类型: string 默认值: 密码强度太低。请使用更强的密码。

当密码未达到最低要求分数时提供的默认消息。

1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/User.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    #[Assert\PasswordStrength([
        'message' => 'Your password is too easy to guess. Company\'s security policy requires to use a stronger password.'
    ])]
    protected $rawPassword;
}

自定义密码强度评估

7.2

自定义密码强度评估的功能在 Symfony 7.2 中引入。

默认情况下,此约束根据密码的长度和使用的唯一字符数来计算密码的强度。您可以使用以下静态函数获取计算出的密码强度(例如,在用户界面中显示它)

1
2
3
use Symfony\Component\Validator\Constraints\PasswordStrengthValidator;

$passwordEstimatedStrength = PasswordStrengthValidator::estimateStrength($password);

如果您需要覆盖默认的密码强度评估算法,您可以将 Closure 传递给 PasswordStrengthValidator 构造函数(例如,使用 服务闭包)。

首先,在专用的可调用类中创建自定义密码强度评估算法

1
2
3
4
5
6
7
8
9
10
11
12
namespace App\Validator;

class CustomPasswordStrengthEstimator
{
    /**
     * @return PasswordStrength::STRENGTH_*
     */
    public function __invoke(string $password): int
    {
        // Your custom password strength estimation algorithm
    }
}

然后,配置 PasswordStrengthValidator 服务以使用您自己的评估器

1
2
3
4
5
6
7
# config/services.yaml
services:
    custom_password_strength_estimator:
        class: App\Validator\CustomPasswordStrengthEstimator

    Symfony\Component\Validator\Constraints\PasswordStrengthValidator:
        arguments: [!closure '@custom_password_strength_estimator']
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本