我正在关注https://symfony.com/doc/current/security/form_login_setup.html的教程,我希望能够访问用户名。我想让会话存储用户名,但我不知道如何捕获登录用户的用户名。
到目前为止,我在SecurityController中尝试了$username = $request->get('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,
));
}
}
login.html.twig
{% 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');
答案 0 :(得分:4)
如果用户成功登录,您可以在$this->getUser()->getUsername()
的控制器中获取用户名(无论您的getter是什么样的)。
如果用户未成功登录,您可以创建一个Doctrine实体并保持失败的尝试,然后再调用该实体。这取决于你想用它做什么?