I am building a basic Symfony 7.1 application.
I created my own User entity, implementing both Symfony\Component\Security\Core\User\UserInterface
and PasswordAuthenticatedUserInterface
.
I am using the user authentication process as provided by Symfony and I don't want to do anything special but rather play it by the book.
The UserInterface
mandates the method eraseCredentials
and it says in its docs:
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.
My User entity stores its password as a hashed through Symfony's password hasher as defined in the
security.yaml
:
password_hashers:
App\Entity\User:
algorithm: bcrypt
cost: 12
I was still under the impression that I should implement the eraseCredentials
, and at first, I did so like this:
#\App\Entity\User
public function eraseCredentials(): void
{
$this->password = null;
}
This lead to weird behavior, as then my login would not work, and I was stuck in an infinite loop to my login action.
The authentication pretty much worked, during debug I even saw that I am redirected to my proper default_target_path
, yet as soon as it tried to render that page, these messages popped in my dev.log
:
[2024-09-09T11:03:26.901713+00:00] security.DEBUG: Cannot refresh token because user has changed. {"username":"MY_USER","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2024-09-09T11:03:26.902036+00:00] security.DEBUG: Token was deauthenticated after trying to refresh it. [] []
I figured I could just leave the eraseCredentials
method empty:
public function eraseCredentials(): void
{
}
And now I can log in, and the app seemingly works.
Yet, I am wondering if I am missing something here.
What is the intended way to handle the password management here?
As shown in the docs:
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
Note that in this example, that this is only meant to erase plainPassword
, not password
(the PLAIN TEXT password, not the HASHED password).
If you are not storing the plain text password anywhere in your user entity, you can leave eraseCredentials()
unimplemented (as you've already discovered):
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{}
Persisting the plain text password has been considered a bad practice for quite some time, but there could be some circumstances and designs where one may need to store the plain text password in the entity (in memory, without actually persisting it).
Maybe for passing it along to other service in charge of actually hashing the password, etc. In a case like this, eraseCredentials()
would be responsible for making sure that the sensitive values would be cleared before, for example, normalizing/serializing the entity values.