登录

时间:2018-03-17 16:09:49

标签: php symfony login yaml credentials

学习Symfony是一段艰难的旅程,我知道关于SO的帖子会随之而来,所以这是我的问题:经典登录页面,我跟着this tutorial,之前我跟着registration form教程。

注册工作正常,用户使用正确的信息插入数据库,问题是登录,因为无论我尝试过什么,都会弹出无效凭据错误消息,我尝试了多个用户,但没有,我找不到错误,一切似乎都是正确的,我已经检查了很多次。所以,我想时间显示一些代码:

我的登录表单:

<form class="form-horizontal" role="form" method="POST" action="{{ path('login') }}">
...
...
<input type="text" name="_username" class="form-control" id="name"
                                   placeholder="Your username" value="{{ last_username }}" required autofocus>
...
...
<input type="password" name="_password" class="form-control" id="password"
                                   placeholder="Password" required>
                                   <input type="hidden" name="_target_path" value="/admin" />
                                   <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

我的控制器负责登录:

     /**
     * @Route("/login", name="login")
     * 
     */

    public function login(Request $request, AuthenticationUtils $authenticationUtils)
    {

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

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

        return $this->render('main/login.html.twig', array(
            'last_username' => $lastUsername,
            'error'         => $error,
        ));
    }

基本上是教程中的复制粘贴。我已经在我的security.yalm文件中设置了:

security:
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        the_user_provider:
            entity: 
                class: App\Entity\User
                property: name

    encoders:
        App\Entity\User:
            algorithm: sha512

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~

            # activate different ways to authenticate

            # http_basic: true
            # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

            form_login:
                login_path: login
                check_path: login
                csrf_token_generator: security.csrf.token_manager
            # https://symfony.com/doc/current/security/form_login_setup.html

            provider: the_user_provider

    # 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_USER }
        # - { path: ^/profile, roles: ROLE_USER }

另外,由于我不知道问题是什么,这里是编码用户密码的注册逻辑部分:

public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, Sluggify $sluggify) {
...
...
// 3) Encode the password (you could also do this via Doctrine listener)
            $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

在我的用户实体中,我已经设置了一个plainPassword和getPlainPassword:

     ...
     ...
     /**
     * @ORM\Column(type="string", length=64)
     */

     private $password;

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

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

对于completition,这是 dev.log 文件中的最后一行:

[2018-03-17 16:35:06] request.INFO: Matched route "login". {"route":"login","route_parameters":{"_controller":"App\\Controller\\MainController::login","_route":"login"},"request_uri":"http://127.0.0.1:8000/login","method":"POST"} []
[2018-03-17 16:35:06] doctrine.DEBUG: SELECT t0.id AS id_1, t0.name AS name_2, t0.email AS email_3, t0.slug AS slug_4, t0.avatar AS avatar_5, t0.password AS password_6, t0.is_author AS is_author_7, t0.is_active AS is_active_8 FROM user t0 WHERE t0.name = ? LIMIT 1 ["K3nzie"] []
[2018-03-17 16:35:06] security.INFO: Authentication request failed. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException(code: 0): Bad credentials. at /home/k3nzie/projects/symfonyWebsite/vendor/symfony/security/Core/Authentication/Provider/UserAuthenticationProvider.php:88, Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException(code: 0): The presented password is invalid. at /home/k3nzie/projects/symfonyWebsite/vendor/symfony/security/Core/Authentication/Provider/DaoAuthenticationProvider.php:65)"} []
[2018-03-17 16:35:06] security.DEBUG: Authentication failure, redirect triggered. {"failure_path":"login"} []
[2018-03-17 16:35:06] request.INFO: Matched route "login". {"route":"login","route_parameters":{"_controller":"App\\Controller\\MainController::login","_route":"login"},"request_uri":"http://127.0.0.1:8000/login","method":"GET"} []
[2018-03-17 16:35:06] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2018-03-17 16:35:07] request.INFO: Matched route "_wdt". {"route":"_wdt","route_parameters":{"_controller":"web_profiler.controller.profiler:toolbarAction","token":"62995d","_route":"_wdt"},"request_uri":"http://127.0.0.1:8000/_wdt/62995d","method":"GET"} []

有什么建议吗?我看了一整天的解决方案,我确定这是一个愚蠢的初学者错误,但仍然......没有。

2 个答案:

答案 0 :(得分:2)

在这段代码中查看问题:

/**
 * @ORM\Column(type="string", length=64)
 */

 private $password;

SHA512实际上返回一个长度为128的字符串。因此,简短的答案是,您的字段仅需为128个字符。

您应该将长度设置为128或更大,或者根本不设置长度,默认情况下它将设置为255

/**
 * @ORM\Column(type="string")
 */

 private $password;

在更改之后,您应该手动或通过迁移来固定数据库表中的字段长度。

答案 1 :(得分:0)

我遇到了同样的问题。尝试更改$ user-&gt; getPlainPassword()。我相信getPlainPassword是一个表单构建器函数,您已经创建了自己的表单,因此需要将变量与请求对象绑定。

在我的代码中,我这样做了。

$password = $passwordEncoder->encodePassword($user, $params['password']);

/**
 * @Route("/register", name="user_registration")
 */
public function registerAction(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
    $params = $request->request->all();

    if ($request->isMethod("POST")) {
        $user = new User();
        $user->setFname($params["fname"]);
        $user->setLname($params["lname"]);
        $user->setEmail($params["email"]);
        $user->setUsername($params["username"]);
        $user->setCreatedAt(new \DateTime());
        //$user->setPassword($params['password']);

        $password = $passwordEncoder->encodePassword($user, $params['password']);
        $user->setPassword($password);

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user);
        $entityManager->flush();

        return $this->redirectToRoute('login');

    }

    return $this->render(
        'default/register.html.twig'
    );
}