Symfony

Installation

Symfony relies on PHP hashing algorithms to encode passwords. The recommended algorithm is called bcrypt and it's available in PHP 5.5+ via the ext/password extension. If you are using an earlier PHP version, install the password_compat library in your projects to enable bcrypt in PHP 5.3.17+ versions:

$ composer require ircmaxell/password-compat

Usage

Before hashing and verifying passwords, define the algorithm to use in the app/config/security.yml file:

# app/config/security.yml
security:
    # ...

    encoders:
        Symfony\Component\Security\Core\User\User: bcrypt

In case you want to define the cost used to hash the password, define the following configuration:

# app/config/security.yml
security:
    # ...

    encoders:
        Symfony\Component\Security\Core\User\User:
            algorithm: bcrypt
            cost: 12

Hashing a Password

In Symfony 2.6 or newer versions, use the security.password_encoder service:

$hashedPassword = $this->container->get('security.password_encoder')
    ->encodePassword($user, $plainPassword);

$user is the object that represents the user and it must implement the Symfony\Component\Security\Core\User\UserInterface interface.

In previous Symfony versions, use the security.encoder_factory service:

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

Verifying a Password

In Symfony 2.6 or newer versions, use the security.password_encoder service:

$isValid = $this->container->get('security.password_encoder')
    ->isPasswordValid($user, $plainPassword);

$user is the object that represents the user and it must implement the Symfony\Component\Security\Core\User\UserInterface interface.

In previous Symfony versions, use the security.encoder_factory service:

$encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
$isValid = $encoder->isPasswordValid($user->getPassword(), $plainPassword, $user->getSalt());

Resources

  • Security Chapter of the official Symfony Book.
  • Symfony Security tutorials