0
votes

I'm currently creating a Symfony3 application and I'm unable to make my login form working ; I've followed these :

The register system is working but I'm unable to login I'd to know if there is something wrong (there is) with my code :

security.yml

# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
    encoders:
        AppBundle\Entity\Compte:
            algorithm: bcrypt
    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        mysqlprovider:
            entity:
                class: AppBundle:Compte
                property: username
    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: ~
            provider: mysqlprovider
            form_login:
                login_path: connexion
                check_path: connexion
                csrf_token_generator: security.csrf.token_manager
            logout: true
            # activate different ways to authenticate

            # http_basic: ~
            # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: ~
            # http://symfony.com/doc/current/cookbook/security/form_login_setup.html
    access_control:
        - { path: ^/connexion, roles: IS_AUTHENTICATED_ANONYMOUSLY }

AppBundle/Controller/SecurityController.php

namespace AppBundle\Controller;

use AppBundle\Entity\Compte;
use AppBundle\Form\CompteType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;

class SecurityController extends Controller
{
    /**
     * @Route("/connexion", name="Connexion")
     */
    public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        $error = $authenticationUtils->getLastAuthenticationError();

        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('AppBundle:Security:connexion.html.twig', array(
            'last_username' => $lastUsername,
            'error'         => $error,
        ));
    }

    /**
     * @Route("/enregistrement", name="Enregistrement")
     */
    public function registerAction(Request $request)
    {
        $user = new Compte();
        $form = $this->createForm(CompteType::class, $user);

        $form->handleRequest($request);
        if ($form->isSubmitted()) {
            $user->setPassword($this->get('security.password_encoder')->encodePassword($user, $user->getPlainPassword()));
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            return $this->redirectToRoute('Accueil');
        }

        return $this->render(
            'AppBundle:Security:enregistrement.html.twig',
            array('form' => $form->createView())
        );
    }
}

AppBundle/Entity/Compte.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Class Compte
 * @ORM\Entity
 * @ORM\Table(name="Compte")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CompteRepository")
 * @UniqueEntity(fields="email", message="Cette adresse mail est déjà prise !")
 * @UniqueEntity(fields="username", message="Ce nom d'utilisateur est déjà pris !")
 */
class Compte implements UserInterface, \Serializable
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="boolean")
     * @Assert\NotBlank
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", length=24, unique=true)
     * @Assert\NotBlank
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=64, unique=true)
     * @Assert\NotBlank
     * @Assert\Email()
     */
    private $email;

    /**
     * @Assert\NotBlank
     * @Assert\Length(max=4096)
     */
    private $plainPassword;

    /**
     * @ORM\Column(name="`password`", type="string", length=128)
     * @Assert\NotBlank
     */
    private $password;

    /**
     * @ORM\OneToOne(targetEntity="Survivant", inversedBy="compte")
     */
    private $survivant;

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

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    public function setPlainPassword($password)
    {
        $this->plainPassword = $password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function getSalt()
    {
        return null;
    }

    public function eraseCredentials() 
    { 
    }

    public function getRoles() 
    { 
        return array('ROLE_USER'); 
    }

    public function getPassword() 
    { 
        return $this->password; 
    }

    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
        ));
    }

    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
        ) = unserialize($serialized);
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->isActive = true;
    }

    /**
     * Set survivant
     *
     * @param \AppBundle\Entity\Survivant $survivant
     *
     * @return Compte
     */
    public function setSurvivant(\AppBundle\Entity\Survivant $survivant = null)
    {
        $this->survivant = $survivant;

        return $this;
    }

    /**
     * Get survivant
     *
     * @return \AppBundle\Entity\Survivant
     */
    public function getSurvivant()
    {
        return $this->survivant;
    }
}

AppBundle/Resources/views/Security/connexion.html.twig

<body>
    {% if error %}
        <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}

    <form action="{{ path('Connexion') }}" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="_username" value="{{ last_username }}" />

        <label for="password">Password:</label>
        <input type="password" id="password" name="_password" />
        <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
        <button type="submit">login</button>
    </form>
</body>
1
The login form is doing a loop when I try to log in. And I don't even know why ?Evitareti

1 Answers

0
votes

The error was in the security.yml in the tutoriel of Symfony the security.yml looks like this :

# app/config/security.yml
security:
    # ...

    firewalls:
        main:
            anonymous: ~
            form_login:
                login_path: login
                check_path: login

But the login_path and check_path are wrong ; you should use the Route with the / so the Route must looks like this :

# app/config/security.yml
security:
    # ...

    firewalls:
        main:
            anonymous: ~
            form_login:
                login_path: /login
                check_path: /login

I don't know if it's a common error but I hope this will help someone.