11

I have a need to manually encrypt the password in the same way Symfony does it.

$user->setPlainPassword($password);
$userManager->updateUser($user);

This is application code that saves the user password. But it is obviously encrypted (not plain as method says).

How can I manually get the same result for given password?

EDIT1:

The problem is that I want to authenticate user manually in users controller code. I have readable username and password that comes as parameters. I want to return 401 if they to not exist in database.

7
  • 1
    What are ypou using the password for? Commented Jun 6, 2017 at 20:32
  • symfony.com/doc/current/components/security/… Commented Jun 6, 2017 at 22:46
  • @zaph I need the password to compare it with the one in database. Basically I need to authenticate user manually in php code. Commented Jun 7, 2017 at 7:54
  • I just copy-pasted your question title "Manually encrypt user password in Symfony php" to the google. And you won't believe - the first item is exactly what you want. Commented Jun 7, 2017 at 8:22
  • You do not need the password you need a password verifier. A password verifier is a representation of the password that can not be reversed to recover the password. On creation the password is run through the verifier and the result saved. On verification the password to e verified is again run through the verifier and the result compared to the saved verifier. For php there is a simple and secure pair of methods: password_hash() and password_verify(). See passwsord hash & verify Commented Jun 7, 2017 at 12:40

3 Answers 3

33

Symfony comes with a useful command to encode a password the same way it does:

bin/console security:encode-password 'your_plain_password' 'AppBundle\Entity\YourUserClass'
Sign up to request clarification or add additional context in comments.

3 Comments

@eomeroff you could check the security:encode-password source to see how they do it. Seriously, don't be that lazy.
@eomeroff Get an IDE to quickly navigate through the code. For Symfony we mainly used PHPStorm.
Or just look in the symfony console for the possible commands, Simple as bonjour ;)
17

In newer Symfony versions (5.3+) you can do it by running CLI command:

bin/console security:hash-password

Comments

9

Try this in your controller action:

$encoder = $this->get('security.encoder_factory')->getEncoder($userClass);
$encodedPassword = $encoder->encodePassword($plainPassword);

1 Comment

You can use UserPasswordEncoderInterface class too: symfony.com/doc/4.0/security/password_encoding.html

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.