1

I use security.yml to configure password encryption:

encoders:
    Acme\UserBundle\Entity\User:
        algorithm: bcrypt
        cost: 10

Now I want to update user password in my User Entity so somewhere in Entity\User.php I should have something like:

$this->password = password_hash($password, PASSWORD_DEFAULT, ['cost' => 10]);

But let's imagine that sometimes someone will decide to change for example encryption cost value to 20 and will update security.yml. It's easy to forget about custom encryption code.

Can I use settings from security.yml in my code to make solution more generalized and friendly for changes?

2 Answers 2

1

It's a bit challenging to directly pull stuff out of security.yml and you really don't want to. You can just use the same password encoder that the security system uses.

$encoderFactory = $this->get('security.encoder_factory');

$encoder = $encoderFactory->getEncoder($user);

$passwordEncrypted = $encoder->encodePassword($passwordPlaintext,$user->getSalt());

Might consider taking a look at the FOSUserBundle UserManager class. It has some useful techniques.

Sign up to request clarification or add additional context in comments.

Comments

0

You should not manually encode a password inside the entity. Better is to leave the entity completely agnostic, and to just pass the encoded result to setPassword().

You can however still do it manually outside the entity, for example in a service, and in that case it is better to get the password encoder factory service from the container (or even better inject it) instead of trying to reproduce the algorithm yourself:

$encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
$user->setPassword($encoder->encodePassword('p4ssw0rd', $user->getSalt()));

Also, an added benefit of using Bcrypt is that you can change the cost at any time without needing to worry to update all passwords in the database at the same time. It will still be able to check passwords with the old settings, and you could for example update the password in the database with the stronger security settings on the next login instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.