【问题标题】:Symfony "Invalid credentials"Symfony“无效凭据”
【发布时间】:2021-09-09 15:22:04
【问题描述】:

我正在开发我的第一个 Symfony 项目,到目前为止,除了登录之外一切都很好,因为每次我尝试登录时都会弹出“无效凭据”警告,但我不知道为什么,因为我使用的是 AbstractLoginFormAuthenticator AbstractFormLoginAuthenticator(我看到最多的那个),这让我有点抓狂,因为没有太多信息。

用户实体:

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @method string getUserIdentifier()
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=false)
     */
    private $name;

    /**
     * @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")
     */
    private $password;

    /**
     * @ORM\OneToMany(targetEntity="Booking", mappedBy="user")
     */
    private $userBooking;

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     */
    public function setEmail($email): void
    {
        $this->email = $email;
    }

    /**
     * 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 PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Returning a salt is only needed, if you are not using a modern
     * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
     *
     * @see UserInterface
     */
    public function getSalt(): ?string
    {
        return null;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }
}

安全控制器:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="app_login")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        // if ($this->getUser()) {
        //     return $this->redirectToRoute('target_path');
        // }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
    }

    /**
     * @Route("/logout", name="app_logout")
     */
    public function logout()
    {
        throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
    }
}

登录表单验证器:

<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
    use TargetPathTrait;

    public const LOGIN_ROUTE = 'app_login';

    private UrlGeneratorInterface $urlGenerator;

    public function __construct(UrlGeneratorInterface $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    public function authenticate(Request $request): PassportInterface
    {
        $email = $request->request->get('email', '');

        $request->getSession()->set(Security::LAST_USERNAME, $email);

        return new Passport(
            new UserBadge($email),
            new PasswordCredentials($request->request->get('password', '')),
            [
                new CsrfTokenBadge('authenticate', $request->get('_csrf_token')),
            ]
        );
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
            return new RedirectResponse($targetPath);
        }

        // For example:
        //return new RedirectResponse($this->urlGenerator->generate('some_route'));
        //throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
        return new RedirectResponse('home');
    }

    protected function getLoginUrl(Request $request): string
    {
        return $this->urlGenerator->generate(self::LOGIN_ROUTE);
    }
}

创建用户:

<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\UserTypeUser;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class NewUserController extends AbstractController
{
    #[Route('/newuser', name: 'new_user', methods: ['GET', 'POST'])]
    public function index(Request $request): Response
    {
        $user = new User();
        $form = $this->createForm(UserTypeUser::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->setRoles(['ROLE_USER']);
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            return $this->redirectToRoute('home');
        }

        return $this->render('new_user/index.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }
}

非常感谢。

【问题讨论】:

  • 这看起来不错。你如何创建用户?您是否使用 Symfony 的 UserPasswordHasher(如果您还没有使用 Symfony 5.3,则使用编码器而不是哈希器)对密码进行哈希处理?
  • 我使用 maker bundle 创建了用户。我没有对密码进行编码,“算法”字段目前设置为“自动”。我想我将尝试删除当前的登录文件并再次安装它,并将 enable_authenticator_manager 设置为 false,因为我意识到我将其设置为 true,这就是我获得实验性身份验证器的原因。
  • 没关系。实验性并不意味着它不起作用或粗略。这只是意味着在版本之间可能需要考虑一些更改。我认为问题在于您如何注册/注册/创建用户。可以加代码吗?
  • 当然,即使它是我用于用户从 CRUD 创建的相同代码,只是不在同一个文件中。

标签: php symfony authentication entity symfony5


【解决方案1】:

在您的NewUserController 中,您需要在持久化用户之前对密码进行哈希处理。

首先你需要将服务注入到控制器中:

private $passwordHasher;

public function __construct(UserPasswordHasherInterface $passwordHasher)
{
    $this->passwordHasher = $passwordHasher;
}

然后在您的操作中,您需要在 if 条件中添加一行:

if ($form->isSubmitted() && $form->isValid()) {
    $user->setRoles(['ROLE_USER']);

    $user->setPassword($this->passwordHasher->hashPassword($user, $user->getPassword());

    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->persist($user);
    $entityManager->flush();

    return $this->redirectToRoute('home');
}

这假设您已经在表单中设置了密码,但尚未正确编码。您可以在此处的文档中找到它:https://symfony.com/doc/current/security.html#c-hashing-passwords

请注意,在 Symfony 5.3 之前,密码散列器被称为密码编码器并存在于安全组件中。代码基本相同,但类看起来有点不同。见:https://symfony.com/doc/5.2/security.html#c-encoding-passwords

【讨论】:

  • 非常感谢,没有意识到默认情况下应用程序会读取所有已编码的密码,即使是未编码的密码(我用于测试应用程序的所有帐户都已手动插入数据库)所以我现在肯定会在未来的项目中考虑到这一点。有什么办法可以禁用编码器?
  • 如果您只想直接在数据库中添加帐户,您还可以使用控制台命令对密码进行哈希处理,然后复制:php bin/console security:encode-password(您可以在相同的文档中找到它部分在最后)。
  • 您可以使用明文散列器有效地禁用散列器。只需在 security.yaml 中将 auto 更改为纯文本即可。使用 bin/console security:hash-password 进行确认。
  • 谢谢你们两个:)。
猜你喜欢
  • 2020-08-28
  • 2016-05-20
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 2022-06-11
  • 2018-06-11
  • 2018-11-07
  • 1970-01-01
相关资源
最近更新 更多