我正在尝试在 Symfony 7.1.4 项目中实现安全表单身份验证。使用 POST 类型将表单提交到 /login 路由后没有任何反应。日志中没有错误。知道如何调试吗? 感谢您的帮助。
安全.yaml:
main:
lazy: true
provider: app_user_provider
entry_point: 'form_login'
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
failure_path: /login
default_target_path: /
# target_path_parameter: dashboard
logout:
path: /logout
控制器:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route('/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('prehospsecurity/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}
树枝形态:
{% extends '@CavansitePrehosp/base.html.twig' %}
{% block title %}Log in!{% endblock %}
{% block body %}
<form method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div class="mb-3">
You are logged in as {{ app.user.userIdentifier }}, <a href="{{ path('app_logout') }}">Logout</a>
</div>
{% endif %}
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="username">Username</label>
<input
class="bg-gray-50 border border-gray-300 text-gray-900 rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
type="text" value="{{ last_username }}" name="_username" id="username"
{# class="form-control" #}
autocomplete="username" required autofocus>
<label for="password">Password</label>
<input
class="bg-gray-50 border border-gray-300 text-gray-900 rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white"
type="password" name="_password" id="password"
{# class="form-control" #}
autocomplete="current-password" required>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
<button class="btn btn-lg btn-primary" type="submit">
Sign in
</button>
</form>
{% endblock %}
代码是使用maker包生成的:bin/console make:security:form-login。
由于角色 { path: '^/login$', role: IS_AUTHENTICATED_ANONYMOUSLY } 而不是 { path: '^/login$', role: PUBLIC_ACCESS } 导致无限循环。 自 Symfony 6 以来角色发生了变化,我的错:(