Symfony 3认证/登录表单不起作用。

3

我正在使用Symfony 3创建一个应用程序,用于预订射击场的车道。我遵循Symfony 3文档设置和配置登录和注册表单。我的注册表单可以工作,但我的登录表单无法工作。无论如何,我都会收到“无效凭据”的返回。

以下是我的安全性YML。

# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
    hide_user_not_found: false
    encoders:
        AppBundle\Entity\User:
            algorithm: bcrypt

    # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
    providers:
        our_db_provider:
            entity:
                class: AppBundle:User

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/
            provider: our_db_provider
            form_login:
                login_path: /login
                check_path: /login_check
                csrf_token_generator: security.csrf.token_manager
                username_parameter: _username
                password_parameter: _password
            logout: true
            anonymous: true

    access_control:
        - { path: ^/profile, roles: ROLE_USER }
        - { path: ^/reservation, roles: ROLE_USER }

这是我的登录控制器。

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Form\UserType;
use AppBundle\Entity\User;

class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function loginAction(Request $request)
    {

        // loads security utilities
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        // renders route
        return $this->render('default/login.html.twig', [
            'year'      => date("Y"),
            'error'     => $error,
            'last_user' => $lastUsername,
        ]);
    }

    /**
     * @Route("/login_check", name="login_check")
     */
    public function loginCheckAction()
    {
    }
}

这是我的代码仓库,你可以使用电子邮件或用户名进行登录。

<?php

namespace AppBundle\Repository;

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository implements UserLoaderInterface {
    public function loadUserByUsername($username)
    {
        $user = $this->createQueryBuilder('u')
            ->where('u.username = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery()
            ->getOneOrNullResult();

        if (null === $user) {
            $message = sprintf(
                'Unable to find an active admin AppBundle:User object identified by "%s".',
                $username
            );
            throw new UsernameNotFoundException($message);
        }

        return $user;
    } }

这是我的用户实体(Entity)

<?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;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

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

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

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

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

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

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

    public function getSalt()
    {
        return null;
    }

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

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

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

    public function eraseCredentials()
    {
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
        ) = unserialize($serialized);
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     *
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     *
     * @return User
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }
}

不确定发生了什么事情,但我真的很需要帮助。

谢谢, 罗伯特


你最初是如何将用户添加到数据库中的?我怀疑密码可能存在编码不当的问题。 - Cerad
我根据Symfony文档使用Doctrine:http://symfony.com/doc/current/cookbook/doctrine/registration_form.html - Robert430404
你的登录表单中有适当的字段名称吗? - Jan Rydrych
是的,_username和_password我完全按照文档操作了。 - Robert430404
1个回答

2

快速概述说您忘记向提供者配置中添加属性字段。也许,问题不在于此,但无论如何:

providers:
    our_db_provider:
        entity:
            class: AppBundle:User
            property: username

我建议在实体的setter中对密码进行编码:
public function setPassword($password) {
    if ($password)
        $this->Password = password_hash($password, PASSWORD_DEFAULT);

    return $this;
}

请确保您数据库中的密码已经进行了编码。如果您存储了未编码的密码,您将无法使用它。只需前往phpMyAdmin或任何其他工具进行检查即可。也许,在创建用户时出现了错误。


1
我知道它们被编码了,我正在使用根据文档实现的自定义存储库。这就是为什么用户名属性不存在的原因。 - Robert430404

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接