php - Why user is still anonymous when I try log in - Symfony 5?

I'm a new symfony developer and I'm facing a new problem. I've created an authentication system using the guard system. However, when I try to log in entering my email and password, the user is still anonymous. Here is my code :
User.php
:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Exception;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="App\Repository\UsersRepository")
* @UniqueEntity(fields={"email"}, message="Un compte existe dГ©jГ avec cet email.")
*/
class User implements UserInterface
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
* @Assert\NotBlank
* @ORM\Column(name="name", type="string", length=150, nullable=false)
*/
private $name;
/**
* @var string
* @Assert\NotBlank
* @ORM\Column(name="firstname", type="string", length=255, nullable=false)
*/
private $firstname;
/**
* @var string
* @Assert\NotBlank
* @Assert\Regex(
* pattern="/^(0|(\+)33)([1-9])([0-9]){8}$/",
* match=true,
* message="Entrez un numГ©ro de tГ©lГ©phone valide, s'il vous plaГ®t."
* )
* @ORM\Column(name="phone", type="string", length=10, nullable=false)
*/
private $phone;
/**
* @var string
* @ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $email;
/**
* @var string
* @Assert\NotBlank
* @Assert\Regex(
* pattern="/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@?!$£€*]){8,}/",
* match=true,
* message="Votre mot de pass doit être une combinaison de 8 caractères contenant une majuscule, une minuscule, un chiffre et au moins un symbole spécial : @?!$£€*."
* )
* @ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* @var string
*
* @ORM\Column(name="payment_method", type="string", length=255, nullable=true)
*/
private $paymentMethod;
/**
* @var \DateTime|null
*
* @ORM\Column(name="payment_date", type="datetime", nullable=true)
*/
private $paymentDate;
/**
* @var \DateTime
*
* @ORM\Column(name="creation_date", type="datetime", nullable=true, options={"default"="CURRENT_TIMESTAMP"})
*/
private $creationDate;
/**
* @ORM\Column(type="string", length=255)
*/
private $roles;
/**
* @ORM\Column(type="boolean", nullable=false)
*/
private $isVerified = false;
/**
* User constructor.
*/
public function __construct()
{
$this->creationDate = new \DateTime();
$this-> roles = 'ROLE_USER';
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getPaymentMethod(): ?string
{
return $this->paymentMethod;
}
public function setPaymentMethod(string $paymentMethod): self
{
$this->paymentMethod = $paymentMethod;
return $this;
}
public function getPaymentDate(): ?\DateTimeInterface
{
return $this->paymentDate;
}
public function setPaymentDate(?\DateTimeInterface $paymentDate): self
{
$this->paymentDate = $paymentDate;
return $this;
}
public function getCreationDate(): ?\DateTimeInterface
{
return $this->creationDate;
}
public function setCreationDate(\DateTimeInterface $creationDate): self
{
$this->creationDate = $creationDate;
return $this;
}
public function getRoles(): string
{
return $this->roles;
}
public function setRoles(string $roles): self
{
$this->roles = $roles;
return $this;
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getUsername()
{
return $this->email;
}
}
SecurityController.php
:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="app_login")
* @param AuthenticationUtils $authenticationUtils
* @return Response
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('home.html.twig');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}
security.yaml
:
security:
encoders:
App\Entity\Users:
algorithm: auto
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
lazy: true
provider: app_user_provider
guard:
authenticators:
- App\Security\UserAuthenticator
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
login.html.twig
:
{% extends 'base.html.twig' %}
{% block title %}Log in!{% endblock %}
{% block body %}
<form class="container mt-5 pb-4" style="width: 35%; method=" post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div class="mb-3">
You are logged in as {{ app.user.username }}, <a href="{{ path('app_logout') }}">Logout</a>
</div>
{% endif %}
<h3 class="text-center pb-3">Se connecter</h3>
<div class="row pb-4">
<label for="inputEmail">Email</label>
<input type="email" value="{{ last_username }}" name="email" id="inputEmail" class="form-control" required
autofocus>
</div>
<div class="row pb-4">
<label for="inputPassword">Mot de passe</label>
<input type="password" name="password" id="inputPassword" class="form-control" required>
</div>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{#
Uncomment this section and add a remember_me option below your firewall to activate remember me functionality.
See https://symfony.com/doc/current/security/remember_me.html
<div class="checkbox mb-3">
<label>
<input type="checkbox" name="_remember_me"> Remember me
</label>
</div>
#}
<div class="text-center">
<button class="btn btn-success" type="submit">Connexion</button>
</div>
</form>
{% endblock %}
N.B : I want to check if the credentials I'm entering in the login form exist in DB, then you can log into your account otherwise you cannot go through the firewall and access your account.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: constant expression contains invalid operations
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.