代码之家  ›  专栏  ›  技术社区  ›  shaelex

Symfony 4 |访问通过传统用户表单传递的用户名(来自doc)

  •  3
  • shaelex  · 技术社区  · 8 年前

    我正在学习 https://symfony.com/doc/current/security/form_login_setup.html 我想访问用户名。我想让会话存储用户名,但我不知道如何捕获登录用户的用户名。

    到目前为止我已经试过了 $username = $request->get('username'); 在SecurityController中,然后尝试将会话“username”密钥设置为 $username 但它不起作用。

    SecurityController。php

    <?php
    /**
     * Created by PhpStorm.
     * User: Adrian
     * Date: 2018-01-29
     * Time: 11:02
     */
    
    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
    use Symfony\Component\Routing\Annotation\Route;
    
    class SecurityController extends Controller
    {
        /**
         * @Route("/panel/login", name="login")
         */
        public function login(Request $request, AuthenticationUtils $authUtils) {
            $error = $authUtils->getLastAuthenticationError();
            $lastUsername = $authUtils->getLastUsername();
    
            return $this->render('security/login.html.twig', array(
                'last_username' => $lastUsername,
                'error'         => $error,
            ));
        }
    
    }
    

    登录名。html。细枝

    {% block body %}
        {% if error %}
            <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
        {% endif %}
    
        <form action="{{ path('login') }}" 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="_target_path" value="/panel/dashboard"/>
            {#
                If you want to control the URL the user
                is redirected to on success (more details below)
                <input type="hidden" name="_target_path" value="/account" />
            #}
    
            <button type="submit">login</button>
        </form>
    {% endblock %}
    

    稍后,我希望访问此用户名,如下所示:

    $session = $request->getSession();
    $username = $session->get('username');
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   Ollie in PGH    8 年前

    如果用户成功登录,您可以使用 $this->getUser()->getUsername() (无论你的getter看起来像什么)。

    如果用户没有成功登录,您可以创建一个条令实体并保留失败的尝试,然后稍后调用该实体。这取决于你想用它做什么?