Your Location is: Home > Symfony

symfony 4.4 login form

From: Finland View: 4546 808boomm 

Question

I'm posting here because I had searching for hours now. When I was in dev mode, everything was totally working and now, I had push my app on the server, the login form do not work. When I click on "login" we can see the password and the email on the URL (and we stay on the login page) like if I done get method:

"https://website/login?email=blablablamail%40gmail.com&password=paswword&_csrf_token=9fI5G0acHOHQ8rmpO4chM2XrI0Tm8HSN32ghrtRzb38"

I'm using fortrabbit server

-> my swiftmailer function is not working too but I don't know why because the .env is correctly done and the swiftmailer.yaml is ok too, maybe there is a link between this 2 errors.

thanx by advance

here is my .env


###> symfony/framework-bundle ###
APP_ENV=prod
APP_SECRET=959a3e56d7f63b190f107a24fc7eade4
#TRUSTED_PROXIES=127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
#TRUSTED_HOSTS='^localhost|example\.com$'
###< symfony/framework-bundle ###

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#conne$
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# For a PostgreSQL database, use: "postgresql://db_user:[email protected]:5432/db_name?serverVersion=11&charset=utf8"
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
DATABASE_URL=mysql://root:[email protected]:3306/mysuper?serverVersion=10.4.8
###< doctrine/doctrine-bundle ###

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
###< nelmio/cors-bundle ###


here is my security.yaml


security:
    encoders:
        App\Entity\User:
            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: lazy
            provider: app_user_provider
            form_login:
              login_path: app_login
              check_path: app_login
            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: ^/user, roles: ROLE_USER }

    role_hierarchy:
        ROLE_ADMIN: ROLE_USER



here is my user.php


<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;



/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     *
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     *@Assert\Regex(
     *     pattern="/^[a-zA-Z0-9_.-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/",
     *     message="Veuillez indiquer un mail valide"
     * )
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];



    /**
     * @var string The hashed password
     * @ORM\Column(type="string" )
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=25, nullable=true)
     * @Assert\Regex(
     *     pattern="/^[^0-9-<>()\[\]\\.,;:\[email protected]\']+[ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçêëìíîïðòóôõöùúûüýÿ\s]{2,}$/" ,
     *     match=false,
     *     message="Ton prénom ne peux pas contenir de caractères spéciaux"
     * )
     */
    private $prenom;

    /**
     * @ORM\Column(type="string", length=25, nullable=true)
     * @Assert\Regex(
     *     pattern="/^[^0-9-<>()\[\]\\.,;:\[email protected]\']+[ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçêëìíîïðòóôõöùúûüýÿ\s]{2,}$/" ,
     *     match=false,
     *     message="Ton nom ne peux pas contenir de caractères spéciaux"
     * )
     */
    private $nom;

    /**
     * @ORM\Column(type="string", length=10, nullable=true)
     *
     *
     *
     * * @Assert\Regex(
     *     pattern="/^
    (?:(?:\+|00)33|0)     # Dialing code
    \s*[1-9]              # First number (from 1 to 9)
    (?:[\s.-]*\d{2}){4}   # End of the phone number
    $/" ,
     *     match=false,
     *     message="Veuillez écrire un numéro valide"
     * )
     */
    private $phone;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    private $phoneok;

    /**
     * @ORM\OneToMany(targetEntity=Mission::class, mappedBy="User", orphanRemoval=true)
     */
    private $missions;

    public function __construct()
    {
        $this->missions = new ArrayCollection();
    }



    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getPrenom(): ?string
    {
        return $this->prenom;
    }

    public function setPrenom(?string $prenom): self
    {
        $this->prenom = $prenom;

        return $this;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(?string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getPhone(): ?string
    {
        return $this->phone;
    }

    public function setPhone(?string $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getPhoneok(): ?bool
    {
        return $this->phoneok;
    }

    public function setPhoneok(?bool $phoneok): self
    {
        $this->phoneok = $phoneok;

        return $this;
    }

    /**
     * @return Collection|Mission[]
     */
    public function getMissions(): Collection
    {
        return $this->missions;
    }

    public function addMission(Mission $mission): self
    {
        if (!$this->missions->contains($mission)) {
            $this->missions[] = $mission;
            $mission->setUser($this);
        }

        return $this;
    }

    public function removeMission(Mission $mission): self
    {
        if ($this->missions->contains($mission)) {
            $this->missions->removeElement($mission);
            // set the owning side to null (unless already changed)
            if ($mission->getUser() === $this) {
                $mission->setUser(null);
            }
        }

        return $this;
    }


}



here is my security controller

<?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")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        // if ($this->getUser()) {
        //     return $this->redirectToRoute('target_path');
        // }

        // 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.');
    }
}


here is my login form :



{% extends 'base.html.twig' %}

{% block title %}Se connecter{% endblock %}

{% block body %}
<form  action="{{ path('app_login') }}"   method="post "  class="mt-4">
    {% if error %}
        <div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}

    {% if app.user %}
        <div class="mb-3">
            Vous   tes connect   en tant que  {{ app.user.prenom }}, <a href="{{ path('app_logout') }}">Logout</a>
        </div>
    {% endif %}
<div class="container-fluid ">
    <h1 class="h3 mb-3 font-weight-normal">Veuillez vous connecter</h1>
  <label for="inputEmail" class="m-2">Email</label>
    <input type="email" value="{{ last_username }}" name="email" id="inputEmail" class="form-control container-fluid " req$
    <label for="inputPassword" class="m-2">Mot de passe</label>
    <input type="password" name="password" id="inputPassword" class="form-control container-fluid " required>
<br>
    <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>
    #}

    <button class="btn btn-lg btn-primary m-2" type="submit">
        Connexion
    </button>


</div>
</form>
{% endblock %}

Best answer