Symfony安全性在身份验证期间使用了错误的sql表别名

问题描述

我正在尝试创建自己的User实体,以扩展SuluUser实体(以便添加一些属性)。按照Sulu documentation: Extend Entities的说明进行操作后,我为(前端)网站创建了自己的symfony身份验证,但是,当我尝试进行身份验证时,出现以下错误。

编辑:为用户实体添加了导入和注释

执行'SELECT t1.username AS username_2,t1.password AS password_3,t1.locale AS locale_4,t1.salt AS salt_5,t1.locked ASlocked_6,t1.enabled AS enabled_7,t1.lastLogin AS时发生异常lastLogin_8,t1.confirmationKey AS确认密钥_9,t1.passwordResetToken AS passwordResetToken_10,t1.passwordResetTokenExpiresAt AS passwordResetTokenExpiresAt_11,t1.passwordResetTokenEmailsS​​ent已发送AS passwordResetTokenEmailsS​​ent_12,t1.privateKey AS AS1私钥_id,电子邮件t1。 t1.firstname AS firstname_17,t1.lastname AS lastname_18,t1.phonenumber AS phonenumber_19,t1.gender AS sex_20,t1.password_changed_date AS password_changed_date_21,t1.confirmation_token AS Confirmation_token_22,t1.idContacts AS idContacts_E =用户t1 W1。带有参数[“ test@test.com”]的LIMIT 1':

SQLSTATE [42S22]:找不到列:1054'where子句'中的未知列't0.email'

我不确定在其余查询使用t1作为别名时为什么使用t0.email的原因,但这会中断从(前端)网站的登录。管理员可以登录sulu后端就可以了。我相信这与我的User实体扩展的SuluUser继承有关。任何帮助将不胜感激。我已经读过doctrine inheritance here的内容,但我认为这并不适用,因为我不能(不应)更改Sulu \ Bundle \ SecurityBundle \ Entity \ User中的类。我已经配置了以下

App \ Entity \ User

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Sulu\Bundle\SecurityBundle\Entity\User as SuluUser;
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(fields={"email"})
 */
class User extends SuluUser
{

    /**

     * @Groups({"get","post","put","get-comment-with-author","get-blog-post-with-author"})
     * @ORM\Column(type="string",length=25)
     * @Assert\NotBlank(groups={"post"})
     * @Assert\Length(min=4,max="100")
     */
    private $Firstname;

    /**
     * @Groups({"get","put"})
     * @ORM\Column(type="string",max="100")
     */
    private $Lastname;

    /**
     * @ORM\Column(type="string",length=10,nullable=true)
     *
     * @Groups({"get","put"})
     */
    private $phonenumber;

    /**
     * @ORM\Column(type="string",nullable=true)
     * @Groups({"get","put"})
     * @Assert\Collection()
     */
    private $gender;


    /**
     * @Groups({"post"})
     * @Assert\NotBlank(groups={"post"})
     * @Assert\Expression(
     *     "this.getPassword() === this.getRetypedPassword()",*     message="Passwords do not match"
     * )
     */
    private $retypedPassword;


    /**
     * @Assert\Length(min=10,max="100")
     * @Assert\NotBlank(groups={"put-reset-password"})
     * @Groups({"put-reset-password"})
     * @Assert\Regex(
     *     pattern="/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{7,}/",*     message="Your password needs to be at least 10 characters long and contain the folloiwing"
     * )
     */
    private $newPassword;


    /**
     * @Groups({"put-reset-password"})
     * @Assert\NotBlank(groups={"put-reset-password"})
     * @Assert\Expression(
     *     "this.getNewPassword() === this.getNewRetypedPassword()",*     message="Passwords does not match",*     groups={"put-reset-password"}
     * )
     */
    private $newRetypedPassword;


    /**
     * @Groups({"put-reset-password"})
     * @Assert\NotBlank(groups={"put-reset-password"})
     * @UserPassword(groups={"put-reset-password"})
     */
    private $oldPassword;
    /**
     * @ORM\Column(type="integer",nullable=true)
     */
    private $passwordChangedDate;

    /**
     * @ORM\Column(type="string",length=40,nullable=true)
     */
    private $confirmationToken;


    public function __construct()
    {
        $this->confirmationToken = null;

    }


    public function getFirstname(): ?string
    {
        return $this->Firstname;
    }

    public function setFirstname( $Firstname): self
    {
        $this->Firstname = $Firstname;

        return $this;
    }

    public function getLastname(): ?string
    {
        return $this->Lastname;
    }

    public function setLastname( $Lastname): self
    {
        $this->Lastname = $Lastname;

        return $this;
    }

    public function getPhonenumber(): ?string
    {
        return $this->phonenumber;
    }

    public function setPhonenumber(?string $phonenumber): self
    {
        $this->phonenumber = $phonenumber;

        return $this;
    }

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

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


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

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

    public function getNewPassword(): ?string
    {
        return $this->newPassword;
    }

    public function setNewPassword($newPassword): void
    {
        $this->newPassword = $newPassword;
    }

    public function getNewRetypedPassword(): ?string
    {
        return $this->newRetypedPassword;
    }

    public function setNewRetypedPassword($newRetypedPassword): void
    {
        $this->newRetypedPassword = $newRetypedPassword;
    }

    public function getOldPassword(): ?string
    {
        return $this->oldPassword;
    }

    public function setOldPassword($oldPassword): void
    {
        $this->oldPassword = $oldPassword;
    }

    public function getPasswordChangedDate()
    {
        return $this->passwordChangedDate;
    }

    public function setPasswordChangedDate($passwordChangedDate): void
    {
        $this->passwordChangedDate = $passwordChangedDate;
    }


    public function getConfirmationToken()
    {
        return $this->confirmationToken;
    }


    public function setConfirmationToken($confirmationToken): void
    {
        $this->confirmationToken = $confirmationToken;
    }



    public function __toString(): string
    {
        return $this->Firstname . ' ' . $this->Lastname;
    }

}

App \ config \ packges \ security_website.yaml

security:
  encoders:
    App\Entity\User:
      algorithm: auto


  providers:
    app_user_provider:
      entity:
        class: App\Entity\User
        property: email
  firewalls:
    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    main:
      anonymous: false
      lazy: true
      provider: app_user_provider
      guard:
        authenticators:
          - App\Security\AppAuthenticator
      logout:
        path: app_logout
        # where to redirect after logout
        target: home

App \ Security \ AppAuthenticator

class AppAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
    use TargetPathTrait;

    public const LOGIN_ROUTE = 'app.login';

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(EntityManagerInterface $entityManager,UrlGeneratorInterface $urlGenerator,CsrfTokenManagerInterface $csrfTokenManager,UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function supports(Request $request)
    {
        return self::LOGIN_ROUTE === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'email' => $request->request->get('email'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),];
        $request->getSession()->set(
            Security::LAST_USERNAME,$credentials['email']
        );

        return $credentials;
    }

    public function getUser($credentials,UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate',$credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('Email could not be found.');
        }

        return $user;
    }

    public function checkCredentials($credentials,UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user,$credentials['password']);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function getPassword($credentials): ?string
    {
        return $credentials['password'];
    }

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

        $role =  $token->getUser()->getRoles();

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

                return new RedirectResponse('/');


    }

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

解决方法

当您覆盖在同一表名上设置的Sulu实体时,这非常重要,否则该实体的替代将无法正常工作,例如在documentation中使用“ se_users”设置@ORM \ Table和@ORM \ Entity。

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Sulu\Bundle\SecurityBundle\Entity\User as SuluUser;

/**
 * Following annotations are required and should not be changed:
 *
 * @ORM\Table(name="se_users")
 * @ORM\Entity
 */
class User extends SuluUser
{
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...