He actualizado desde Symfony 5.4.7 a Symfony 5.4.8, y al intentar autenticar vuelve a redireccionar al login pero no me muestra ningún error. La autenticación es a través de un Formulario de Login contra base de datos; expongo la configuración que tengo hasta el momento:
#security.yaml:
security:
enable_authenticator_manager: true
password_hashers:
legacy:
algorithm: sha512
cost: 10
App\Entity\Usuario:
algorithm: 'auto'
cost: 10
migrate_from:
- legacy
providers:
userdb_provider:
entity:
class: App\Entity\Usuario
property: username
manager_name: default
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
app:
pattern: ^/*
provider: userdb_provider
form_login:
login_path: usuario_login
use_forward: true
check_path: usuario_loginCheck
failure_forward: false
require_previous_session: false
enable_csrf: true
always_use_default_target_path: true
logout:
path: usuario_logout
target: app_homepage
csrf_parameter: _csrf_token # Optional (defaults to "_csrf_token")
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
- { path: ^/configurar, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
- { path: ^/configurar/*, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
- { path: ^/*, roles: [IS_AUTHENTICATED_FULLY, ROLE_CONS_NAC, ROLE_ESP_NAC, ROLE_ESP_PROV, ROLE_ESP_MUN, ROLE_ESP_AS, ROLE_EST_AS, ROLE_EST_MUN, ROLE_EST_GBT, ROLE_J_GBT, ROLE_EST_HOSP, ROLE_EST_HOMA, ROLE_MEDICO, ROLE_GENETISTA], requires_channel: https }
role_hierarchy:
ROLE_CONS_NAC: ROLE_CONS_NAC
ROLE_ESP_AS: ROLE_ESP_AS
ROLE_EST_AS: ROLE_EST_MUN
ROLE_ESP_NAC: ROLE_ESP_NAC
ROLE_ESP_PROV: ROLE_ESP_PROV
ROLE_ESP_MUN: ROLE_ESP_MUN
ROLE_EST_MUN: ROLE_EST_MUN
ROLE_J_GBT: ROLE_J_GBT
ROLE_EST_GBT: ROLE_EST_GBT
ROLE_EST_HOSP: ROLE_EST_HOSP
ROLE_EST_HOMA: ROLE_EST_HOMA
ROLE_GENETISTA: ROLE_GENETISTA
ROLE_MEDICO: ROLE_MEDICO
La entidad Usuario (resumida):
namespace App\Entity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Usuario
*
* @ORM\Table(name="usuario")
* @ORM\Entity(repositoryClass="App\Repository\UsuarioRepository")
* @UniqueEntity("username", message="Ya existe un usuario con ese identificador")
*/
class Usuario implements UserInterface, PasswordAuthenticatedUserInterface, EquatableInterface, \Serializable
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\SequenceGenerator(sequenceName="usuario_id_id_seq", initialValue=1, allocationSize=100)
*/
private $id;
/**
* @var string
*
* @Assert\NotBlank(message="El identificador es obligatorio.")
* @ORM\Column(name="username", type="string", unique=true, length=100, nullable=false)
*/
private $username;
/**
* @var string
*
* @Assert\Length(
* min=6,
* max=255,
* minMessage="La contraseña debe tener como mínimo {{ limit }} caracteres",
* maxMessage="La contraseña no puede exceder los {{ limit }} caracteres."
* )
* @ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* @var boolean
*
* @ORM\Column(name="activo", type="boolean", nullable=false)
*/
private $activo;
/**
* @var type \App\Entity\Rol
*
* @ORM\ManyToOne(targetEntity="Rol", fetch="EAGER")
* @ORM\JoinColumn(name="rol_id", referencedColumnName="id", nullable=false, onDelete="RESTRICT")
*/
private $rol;
/**
* Set username
*
* @param string $username
* @return Usuario
*/
public function setUsername(?string $username): self
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername(): string
{
return $this->username;
}
/**
*
* @return array
*/
public function getRoles(): array
{
$coleccion = new ArrayCollection();
$coleccion->add($this->getRol()->getToken());
$coleccion[] = "ROLE_USER";
return array_unique($coleccion->toArray());
}
/**
* Set password
*
* @param string $password
* @return Usuario
*/
public function setPassword(?string $password): self
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* Set activo
*
* @param bool $activo
* @return Usuario
*/
public function setActivo(bool $activo): self
{
$this->activo = $activo;
return $this;
}
/**
* Get activo
*
* @return bool
*/
public function getActivo(): bool
{
return $this->activo;
}
/**
* Get id
*
* @return integer
*/
public function getId(): ?int
{
return $this->id;
}
/**
* Add rol
*
* @param Rol $rol
* @return Usuario
*/
public function setRol(Rol $rol): self
{
$this->rol = $rol;
return $this;
}
/**
*
* @return Rol|null
*/
public function getRol(): ?Rol
{
return $this->rol;
}
/**
*
* @return void
*/
public function eraseCredentials(): void
{
}
/**
*
* @return string
*/
public function getSalt(): string
{
return '';
}
/**
*
* @return bool
*/
public function isAccountNonExpired(): bool
{
return true;
}
/**
*
* @return bool
*/
public function isAccountNonLocked(): bool
{
return true;
}
/**
*
* @return bool
*/
public function isCredentialsNonExpired(): bool
{
return true;
}
/**
*
* @return bool
*/
public function isEnabled(): bool
{
return $this->activo;
}
/**
*
* @return string
*/
public function serialize(): string
{
return serialize([
$this->username,
$this->nombreCompleto,
$this->password,
$this->activo,
$this->id,
$this->idPublico
]);
}
/**
*
* @param type $serialized
* @return void
*/
public function unserialize($serialized): void
{
list(
$this->username,
$this->nombreCompleto,
$this->password,
$this->activo,
$this->id,
$this->idPublico
) = unserialize($serialized);
}
/**
*
* @return array
*/
public function __sleep(): array
{
return ['username', 'nombreCompleto', 'password', 'activo', 'id', 'idPublico'];
}
/**
*
* @return string
*/
public function __toString(): string
{
return $this->nombreCompleto;
}
/**
*
* @param UserInterface $user
* @return bool
*/
public function isEqualTo(UserInterface $user): bool
{
if ($this->getUsername() === $user->getUsername() && $this->getPassword() === $user->getPassword() && $this->getSalt() === $user->getSalt() && $this->isEnabled() === $user->isEnabled()) {
return true;
}
return false;
}
/**
* @return string
* * */
public function getUserIdentifier(): string
{
return (string) $this->username;
}
}
La clase UsuarioRepository:
namespace App\Repository;
use App\Entity\EstructuraOrganizativa;
use App\Entity\Usuario;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\NoResultException;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Description of UsuarioRepository
*
*/
class UsuarioRepository extends ServiceEntityRepository implements UserLoaderInterface, PasswordUpgraderInterface
{
/**
*
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Usuario::class);
}
/**
*
* @param string $username
* @return Usuario|null
* @throws UsernameNotFoundException
*/
public function loadUserByIdentifier(string $username): ?Usuario
{
$dql = "SELECT u, b r, eo, teo FROM App:Usuario u LEFT JOIN u.buzonInterno b JOIN u.rol r JOIN u.estructuraOrganizativa eo JOIN eo.tipoEstructuraOrganizativa teo WHERE u.username = :username AND r.id IN (SELECT rr.id FROM App:Rol rr WHERE rr.habilitado = true)";
$query = $this->getEntityManager()->createQuery($dql);
$query->setParameter('username', $username);
$query->setMaxResults(1);
$query->useQueryCache(true);
return $query->getOneOrNullResult();
}
/**
*
* @param type $username
* @return Usuario|null
* @throws UsernameNotFoundException
*/
public function loadUserByUsername(string $username): ?Usuario
{
return $this->loadUserByIdentifier($username);
}
/**
*
* @param UserInterface $user
* @return Usuario|null
* @throws UnsupportedUserException
*/
public function refreshUser(UserInterface $user)
{
$class = \get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.', $class
)
);
}
return $this->findOneJoinedEstructuraOrganizativa($user->getId());
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*
* @param UserInterface $user
* @param string $newHashedPassword
* @throws UnsupportedUserException
*/
public function upgradePassword(UserInterface $user, string $newHashedPassword): void
{
if (!$user instanceof Usuario) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
}
$user->setPassword($newHashedPassword);
$this->_em->persist($user);
$this->_em->flush();
}
}
Y por ulitmo el action que maneja el formulario de login:
/**
*
* @param AuthenticationUtils $authUtils
* @param ManagerRegistry $manager
* @return Response
*/
public function renderLoginFormAction(AuthenticationUtils $authUtils, ManagerRegistry $manager)
{
$error = $authUtils->getLastAuthenticationError();
$ultimoUsuario = $authUtils->getLastUsername();
return $this->render('Usuario/login.html.twig', [
'last_username' => $ultimoUsuario,
'error' => $error,
]);
}