简体   繁体   English

如何在Symfony2中设置密码长度限制?

[英]How to set password length constraints in Symfony2?

I tried with @Assert\\MinLength but it seems to check after encoding the password when it's long enought in everycase. 我尝试使用@Assert\\MinLength但是在每种情况下密码足够长时,似乎都在对密码进行编码后进行检查。 How to put the constraint before encoding? 如何在编码之前放置约束?

I can't think of anything better that to count the number of symbols with strlen after binding the registration form, but I don't think this will be a good way. 我想不出什么更好的主意,要数与符号的数量strlen结合报名表后,但我不认为这将是一个很好的方式。 And also I'm not sure that even this will work, I'm not sure when exactly the encoding is done. 而且我不确定即使这样也能正常工作,也不确定何时完成编码。

Any suggestions will be appreciated! 任何建议将不胜感激! Thank you in advance! 先感谢您!

The problem is that you're using one field for two purposes: storing a password in plain text and encoded form. 问题是您将一个字段用于两个目的:以纯文本和编码形式存储密码。 What you need is a field for each purpose: 您需要的是一个用于各种用途的字段:

use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\MinLength;
use Doctrine\ORM\Mapping\Column;

class User 
{
    /**
     * @NotBlank
     * @MinLength(6)
     *
     * @var string
     */
    private $plainPassword;

    /**
     * @Column
     *
     * @var string
     */
    private $password;
}

Only the $password field is persisted to the database and it's not shown in forms so that users can't edit it. 只有$password字段会保留在数据库中,并且不会以表格形式显示,因此用户无法对其进行编辑。

Also you need a Doctrine event listener — or some other code — that checks if $plainPassword is not empty, and if it's not, encode its value and put it into $password . 另外,您还需要一个Doctrine事件侦听器(或其他一些代码)来检查$plainPassword是否不为空,如果不是,则对其值进行编码并将其放入$password

Use the security.encoder_factory service to get the encoder you've setup in your security configuration and use it to encode passwords. 使用security.encoder_factory服务获取在安全配置中设置的编码器,并使用它对密码进行编码。 Also, check my ElnurBlowfishPasswordEncoderBundle . 另外,检查我的ElnurBlowfishPasswordEncoderBundle

You shouldn't encode password by yourself in password setter. 您不应该自己在密码设置器中对密码进行编码。 Instead of that use some encoder (you even can write your own encoder), and encode password after form is validated. 而不是使用一些编码器(您甚至可以编写自己的编码器),并在验证表单后对密码进行编码。

Here is example how you use encoders: 这是使用编码器的示例:

http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM