【发布时间】:2018-07-08 04:00:30
【问题描述】:
我正在关注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');
【问题讨论】: