Php 无效凭据身份验证问题symfony 4
在symfony4中,我想创建一个简单的身份验证表单。我创建了一个用户类(标识符是电子邮件字段,而不是用户名),我创建了一个类控制器并配置了security.yml文件 但是,当我进入表单页面并尝试登录(填写电子邮件/密码字段并单击提交按钮)时,会出现错误“无效凭据” 安全.yamlPhp 无效凭据身份验证问题symfony 4,php,symfony,symfony4,Php,Symfony,Symfony4,在symfony4中,我想创建一个简单的身份验证表单。我创建了一个用户类(标识符是电子邮件字段,而不是用户名),我创建了一个类控制器并配置了security.yml文件 但是,当我进入表单页面并尝试登录(填写电子邮件/密码字段并单击提交按钮)时,会出现错误“无效凭据” 安全.yaml encoders: App\Entity\User: algorithm: argon2i # https://symfony.com/doc/curre
encoders:
App\Entity\User:
algorithm: argon2i
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: /logout
#ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
# 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_ADMIN }
- { path: ^/profile, roles: ROLE_USER }
user.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User implements UserInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string",length=255)
*/
private $password;
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getAdresse(): ?string
{
return $this->adresse;
}
public function setAdresse(?string $adresse): self
{
$this->adresse = $adresse;
return $this;
}
public function getTelephone(): ?string
{
return $this->telephone;
}
public function setTelephone(?string $telephone): self
{
$this->telephone = $telephone;
return $this;
}
public function getSexe(): ?string
{
return $this->sexe;
}
public function setSexe(?string $sexe): self
{
$this->sexe = $sexe;
return $this;
}
/**
* @return Collection|Eleve[]
*/
public function getElevesUser1(): Collection
{
return $this->elevesUser1;
}
public function addElevesUser1(Eleve $elevesUser1): self
{
if (!$this->elevesUser1->contains($elevesUser1)) {
$this->elevesUser1[] = $elevesUser1;
$elevesUser1->setUsertuteur1($this);
}
return $this;
}
public function removeElevesUser1(Eleve $elevesUser1): self
{
if ($this->elevesUser1->contains($elevesUser1)) {
$this->elevesUser1->removeElement($elevesUser1);
// set the owning side to null (unless already changed)
if ($elevesUser1->getUsertuteur1() === $this) {
$elevesUser1->setUsertuteur1(null);
}
}
return $this;
}
/**
* @return Collection|Eleve[]
*/
public function getElevesuser2(): Collection
{
return $this->elevesuser2;
}
public function addElevesuser2(Eleve $elevesuser2): self
{
if (!$this->elevesuser2->contains($elevesuser2)) {
$this->elevesuser2[] = $elevesuser2;
$elevesuser2->setUsertuteur2($this);
}
return $this;
}
public function removeElevesuser2(Eleve $elevesuser2): self
{
if ($this->elevesuser2->contains($elevesuser2)) {
$this->elevesuser2->removeElement($elevesuser2);
// set the owning side to null (unless already changed)
if ($elevesuser2->getUsertuteur2() === $this) {
$elevesuser2->setUsertuteur2(null);
}
}
return $this;
}
/**
* @return Collection|profClasse[]
*/
public function getProfsClasse(): Collection
{
return $this->profsClasse;
}
public function addProfsClasse(profClasse $profsClasse): self
{
if (!$this->profsClasse->contains($profsClasse)) {
$this->profsClasse[] = $profsClasse;
$profsClasse->setUser($this);
}
return $this;
}
public function removeProfsClasse(profClasse $profsClasse): self
{
if ($this->profsClasse->contains($profsClasse)) {
$this->profsClasse->removeElement($profsClasse);
// set the owning side to null (unless already changed)
if ($profsClasse->getUser() === $this) {
$profsClasse->setUser(null);
}
}
return $this;
}
public function getCategorie(): ?Categorie
{
return $this->categorie;
}
public function setCategorie(?Categorie $categorie): self
{
$this->categorie = $categorie;
return $this;
}
}
问题可能位于您的
LoginFormAuthenticator
中。
guard认证系统依赖于这样一个类
此外,您还可以使用symfony表单来创建登录页面,而不是“好的旧html表单”。因此,您不必定义普通html,只需通过标准form.html.twig将表单作为任何其他表单输出即可
{% extends '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 %}
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail" class="sr-only">Email</label>
<input type="email" value="{{ last_username }}" name="email" id="inputEmail" class="form-control" placeholder="Email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{#
Uncomment this section and add a remember_me option below your firewall to activate remember me functionality.
See https://symfony.com/doc/current/security/remember_me.html
<div class="checkbox mb-3">
<label>
<input type="checkbox" name="_remember_me"> Remember me
</label>
</div>
#}
<button class="btn btn-lg btn-primary" type="submit">
Sign in
</button>
</form>
{% endblock %}
loginFormAuthenticator
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
在你的控制器里
/**
* @Route("/login", name="security-login")
*/
public function login(Request $request, AuthenticationUtils $authenticationUtils): Response
{
if($this->isGranted('IS_AUTHENTICATED_FULLY'))
return $this->redirectToRoute('index');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$data = [];
$builder = $this->createFormBuilder($data, ['csrf_token_id' => 'authenticate']);
$builder->add('username', TextType::class,[
'label' => 'Benutzername'
])->add('password', PasswordType::class, [
'label' => "Passwort"
])->add('save', SubmitType::class, [
'label' => 'Anmelden'
]);
$response = new Response('');
$form = $builder->getForm();
if($error){
$response->setStatusCode(401);
if($error instanceof BadCredentialsException){
$form->get('password')->addError(new FormError("Das Passwort ist falsch."));
} else if( $error instanceof CustomUserMessageAuthenticationException ){
/** @see CustomAuthenticator::getUser() */
if($error->getCode() === 1)
$form->get('username')->addError(new FormError("Der Nutzer existiert, ist aber deaktiviert. Kontaktieren Sie einen Administrator."));
else if($error->getCode() === 0)
$form->get('username')->addError(new FormError("Der Nutzer ist unbekannt."));
} else {
$form->get('user')->addError(new FormError("Unerwarteter Fehler. Bitte kontaktieren Sie den risklytics-Support."));
}
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
}
return $this->render('default/form.html.twig', [
'form' => $form->createView(),
'title' => 'Anmelden'], $response);
}
您已经声明了一个提供者app\u user\u provider:
,但它在防火墙内的任何地方都没有使用。因此,请在main:
中尝试添加:
provider: app_user_provider
如果遇到其他问题,请尝试启用表单登录:
form_login:
check_path: LOGIN_PATH
login_path: LOGIN_PATH
您试图调试该问题的原因是什么?我找不到问题,您试图查找什么?从验证器中的基础知识开始。是否调用了构造函数?是否调用了支持?您也可以尝试暂时删除凭据检查,只需从
getUser
返回一个用户。然后会发生什么?我的登录名FormAuthenticator?我在问题的末尾添加了登录信息。你能告诉我更多吗?谢谢你能进一步解释吗?请不要只提供提示,而是提供适当的解决方案来帮助OP解决问题,但我的答案的第二部分更重要(在我看来)您的问题的解决方案似乎与问题无关。错误“无效凭证”很可能与身份验证器有关,必须由lulu实现
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
/**
* @Route("/login", name="security-login")
*/
public function login(Request $request, AuthenticationUtils $authenticationUtils): Response
{
if($this->isGranted('IS_AUTHENTICATED_FULLY'))
return $this->redirectToRoute('index');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$data = [];
$builder = $this->createFormBuilder($data, ['csrf_token_id' => 'authenticate']);
$builder->add('username', TextType::class,[
'label' => 'Benutzername'
])->add('password', PasswordType::class, [
'label' => "Passwort"
])->add('save', SubmitType::class, [
'label' => 'Anmelden'
]);
$response = new Response('');
$form = $builder->getForm();
if($error){
$response->setStatusCode(401);
if($error instanceof BadCredentialsException){
$form->get('password')->addError(new FormError("Das Passwort ist falsch."));
} else if( $error instanceof CustomUserMessageAuthenticationException ){
/** @see CustomAuthenticator::getUser() */
if($error->getCode() === 1)
$form->get('username')->addError(new FormError("Der Nutzer existiert, ist aber deaktiviert. Kontaktieren Sie einen Administrator."));
else if($error->getCode() === 0)
$form->get('username')->addError(new FormError("Der Nutzer ist unbekannt."));
} else {
$form->get('user')->addError(new FormError("Unerwarteter Fehler. Bitte kontaktieren Sie den risklytics-Support."));
}
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
}
return $this->render('default/form.html.twig', [
'form' => $form->createView(),
'title' => 'Anmelden'], $response);
}
encoders:
App\Entity\User:
algorithm: argon2i
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: /logout
#ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
# 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_ADMIN }
- { path: ^/profile, roles: ROLE_USER }
provider: app_user_provider
form_login:
check_path: LOGIN_PATH
login_path: LOGIN_PATH