在 Symfony2 中验证密码 [英] Validating a password in Symfony2

查看:23
本文介绍了在 Symfony2 中验证密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Symfony2 中组合更改密码功能.我有一个当前密码"字段、一个新密码"字段和一个确认新密码"字段,我目前关注的部分是验证当前密码"字段.

I'm trying to put together a change password feature in Symfony2. I have a "current password" field, a "new password" field and a "confirm new password" field, and the part I'm currently focusing on is validating the "current password" field.

(顺便说一下,我现在意识到像 FOSUserBundle 这样的东西可以为我处理很多这些事情,但是我已经根据官方的 Symfony 文档构建了我的身份验证系统,我现在没有时间重做我的所有身份验证代码.)

(By the way, I realize now that things like FOSUserBundle exist that would take care of a lot of these things for me, but I already built my authentication system based on the official Symfony documentation, and I don't have time right now to redo all my authentication code.)

我正在想象/希望我能做的是创建一个验证回调,内容如下:

What I'm imagining/hoping I can do is create a validation callback that says something like this:

// Entity/User.php

public function currentPasswordIsValid(ExecutionContext $context)
{
  $currentPassword = $whatever; // whatever the user submitted as their current password
  $factory = $this->get('security.encoder_factory'); // Getting the factory this way doesn't work in this context.
  $encoder = $factory->getEncoder($this);
  $encryptedCurrentPassword = $encoder->encodePassword($this->getPassword(), $this->getSalt());

  if ($encyptedCurrentPassword != $this->getPassword() {
    $context->addViolation('Current password is not valid', array(), null);
  }
}

正如您在我的评论中所见,上述代码不起作用的原因至少有几个.我只会发布有关这些特定问题的特定问题,但也许我完全是在找错树.这就是为什么我要问整体问题.

As you can see in my comments, there are at least a couple reasons why the above code doesn't work. I would just post specific questions about those particular issues, but maybe I'm barking up the wrong tree altogether. That's why I'm asking the overall question.

那么,我如何验证用户的密码?

So, how can I validate a user's password?

推荐答案

有一个 自 Symfony 2.1 以来的内置约束.

首先,您应该创建一个自定义验证约束.您可以将验证器注册为服务并在其中注入您需要的任何内容.

First, you should create a custom validation constraint. You can register the validator as a service and inject whatever you need in it.

其次,由于您可能不想将当前密码的字段添加到 User 类,只是为了将约束约束到它,您可以使用所谓的 表单模型.本质上,您在 Form\Model 命名空间中创建一个类,该类保存当前密码字段和对用户对象的引用.然后,您可以将自定义约束粘贴到该密码字段.然后根据此表单模型创建密码更改表单类型.

Second, since you probably don't want to add a field for the current password to the User class just to stick the constraint to it, you could use what is called a form model. Essentially, you create a class in the Form\Model namespace that holds the current password field and a reference to the user object. You can stick your custom constraint to that password field then. Then you create your password change form type against this form model.

以下是我的一个项目中的一个约束示例:

Here's an example of a constraint from one of my projects:

<?php
namespace Vendor\Bundle\AppBundle\Validator\Constraints\User;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class CurrentPassword extends Constraint
{
    public $message = "Your current password is not valid";

    /**
     * @return string
     */
    public function validatedBy()
    {
        return 'user.validator.current_password';
    }
}

及其验证器:

<?php
namespace Vendor\Bundle\AppBundle\Validator\Constraints\User;

use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use JMS\DiExtraBundle\Annotation\Validator;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;

/**
 * @Validator("user.validator.current_password")
 */
class CurrentPasswordValidator extends ConstraintValidator
{
    /**
     * @var EncoderFactoryInterface
     */
    private $encoderFactory;

    /**
     * @var SecurityContextInterface
     */
    private $securityContext;

    /**
     * @InjectParams({
     *     "encoderFactory"  = @Inject("security.encoder_factory"),
     *     "securityContext" = @Inject("security.context")
     * })
     *
     * @param EncoderFactoryInterface  $encoderFactory
     * @param SecurityContextInterface $securityContext
     */
    public function __construct(EncoderFactoryInterface  $encoderFactory,
                                SecurityContextInterface $securityContext)
    {
        $this->encoderFactory  = $encoderFactory;
        $this->securityContext = $securityContext;
    }

    /**
     * @param string     $currentPassword
     * @param Constraint $constraint
     * @return boolean
     */
    public function isValid($currentPassword, Constraint $constraint)
    {
        $currentUser = $this->securityContext->getToken()->getUser();
        $encoder = $this->encoderFactory->getEncoder($currentUser);
        $isValid = $encoder->isPasswordValid(
            $currentUser->getPassword(), $currentPassword, null
        );

        if (!$isValid) {
            $this->setMessage($constraint->message);
            return false;
        }

        return true;
    }
}

我使用我的 Blofwish 密码编码器包,所以我没有将 salt 作为第三个参数传递给$encoder->isPasswordValid() 方法,但我认为您可以根据自己的需要调整此示例.

I use my Blofwish password encoder bundle, so I don't pass salt as the third argument to the $encoder->isPasswordValid() method, but I think you'll be able to adapt this example to your needs yourself.

此外,我正在使用 JMSDiExtraBundle 来简化开发,但是您当然可以使用经典的服务容器配置方式.

Also, I'm using JMSDiExtraBundle to simplify development, but you can of course use the classical service container configuration way.

这篇关于在 Symfony2 中验证密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆