密碼強度
驗證給定的密碼是否已達到約束條件所需的最低強度。密碼的強度不是透過一組預定義的規則(包含數字、使用小寫和大寫字元等)來評估,而是透過測量密碼的熵值,根據其長度和使用的獨特字元數量。
適用於 | 屬性或方法 |
類別 | 密碼強度 |
驗證器 | PasswordStrengthValidator |
基本用法
以下約束條件確保 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
type: integer
default: 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
type: string
default: The password strength is too low. Please use a stronger password.
當密碼未達到最低要求分數時提供的預設訊息。
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 授權條款授權。