Symfony provides the PasswordHasher component that allows to hash and verify passwords. This tutorial shows examples how to generate the password hash for a given user in Symfony 7 application.
Before starting, make sure you have installed PasswordHasher component:
composer require symfony/password-hasher
Let's say we have the User
class which implements PasswordAuthenticatedUserInterface
and has password
property:
<?php
namespace App\Entity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
class User implements PasswordAuthenticatedUserInterface
{
private string $password;
public function getPassword(): string { return $this->password;}
public function setPassword(string $password): void { $this->password = $password; }
}
Framework use
In the security.yaml
file, password hasher is configured as follows:
security:
# ...
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: auto
Inject UserPasswordHasherInterface
dependency in your controller or service and use hashPassword
method to generate the password hash for a given user.
<?php
namespace App\Controller;
use App\Entity\User;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/')]
public function index(UserPasswordHasherInterface $passwordHasher): Response
{
$user = new User();
$plaintextPassword = 'pwd123';
$hashedPassword = $passwordHasher->hashPassword($user, $plaintextPassword);
$user->setPassword($hashedPassword);
return new Response($hashedPassword);
}
}
Standalone use
PasswordHasher component can be used in any PHP application independently of the Symfony framework. An instance of password hasher can be created using the PasswordHasherFactory
class.
<?php
use App\Entity\User;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
require_once __DIR__.'/vendor/autoload.php';
$passwordHasherFactory = new PasswordHasherFactory([
PasswordAuthenticatedUserInterface::class => ['algorithm' => 'auto'],
]);
$passwordHasher = new UserPasswordHasher($passwordHasherFactory);
$user = new User();
$plaintextPassword = 'pwd123';
$hashedPassword = $passwordHasher->hashPassword($user, $plaintextPassword);
$user->setPassword($hashedPassword);
echo $hashedPassword;
Leave a Comment
Cancel reply