簡體   English   中英

Symfony3錯誤登錄表單

[英]Symfony3 error login form

我目前正在創建一個Symfony3應用程序,但無法使我的登錄表單正常工作; 我遵循這些:

注冊系統正在運行,但是我無法登錄,我想知道我的代碼是否有問題(有):

安全性

# 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>

錯誤是在Symfony的教師中的security.yml中, security.yml看起來像這樣:

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

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

但是login_path和check_path是錯誤的; 您應該將Route與/一起使用,因此Route必須看起來像這樣:

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

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

我不知道這是否是常見錯誤,但我希望這會對某人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM