Symfony security passwords hash with the PasswordEncoder


The PasswordEncoder the symfony framework secure hashes of passwords in the database is very well suitable also in future to save and configure Central.

The SecurityBundle must if necessary. to be installed:

composer require symfony/security-bundle

Putting this in the security.yaml, you want to use what hashing algorithm for which entity:

security:
    encoders:
        App\Entity\User: bcrypt

The entity must implement the UserInterface:

namespace App\Entity;

use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder; 
use Symfony\Component\Security\Core\User\UserInterface;

class User implements UserInterface{

/**
 * @param string
 *
 * @ORM\Column(type="string", length=100)
 */
protected $password;

/**
 * @return string
 */
public function getPassword()
{
    return $this->password;
}

/**
 * Returns the roles granted to the user.
 *
 * <code>
 * public function getRoles()
 * {
 * return array('ROLE_USER');
 * }
 * </code>
 *
 * Alternatively, the roles might be stored on a ``roles`` property,
 * and populated in any number of different ways when the user object
 * is created.
 *
 * @return (Role|string)[] The user roles
 */
public function getRoles()
{
 return array('ROLE_USER');
}

/**
 * Returns the salt that was originally used to encode the password.
 *
 * This can return null if the password was not encoded using a salt.
 *
 * @return string|null The salt
 */
public function getSalt()
{
 return null;
}

/**
 * Removes sensitive data from the user.
 *
 * This is important if, at any given point, sensitive information like
 * the plain-text password is stored on this object.
 */
public function eraseCredentials()
{

}

Then can you the PasswordEncoder injezieren via dependency injection:

App\Repository\UserRepository:
      - '@security.password_encoder'

and the saving of passwords in the database use (without dependency injection):

/**
 * @param User $user
 * @param string $password
 *
 * @return string
 */
protected function encodePassword($user, $password): string
{
    /** @var UserPasswordEncoder $passwordEncoder */
    $passwordEncoder = $this->container->get('security.password_encoder');
    return $passwordEncoder->encodePassword($user, $password);
}

and to validate passwords during login (with dependency injection:

if(!$this->passwordEncoder->isPasswordValid($user, $password)) {
    throw new UnauthorizedHttpException('invalid login');
}

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>