douyiavxxh02727
2015-07-29 15:58
浏览 22
已采纳

在Symfony2中以编程方式登录自定义实体用户后,“Authenticated No”

Programmatically logging in the user through:

$user = new CustomEntityUser();
$user->setUsername("foo");
$user->setPassword("bar");

$entityManager->persist($user);
$entityManager->flush();

$token = new UsernamePasswordToken($user, $user->getPassword(), "main", $user->getRoles());
$this->get('security.token_storage')->setToken($token);

doesn't authenticate the user properly. The debug bar goes yellow and says: "Authenticated No". The name of the firewall is main.

The user-entity-class has implemented the Serializeable-interface according to documentation.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushou9028 2015-07-29 15:58
    已采纳

    The solution was to have the user-entity-class implement the Symfony\Component\Security\Core\User\EquatableInterface, such as e.g.:

    /**
     * {@inheritdoc}
     */
    public function isEqualTo(UserInterface $user)
    {
        if (! $user instanceof User) {
            return false;
        }
    
        if ($this->username !== $user->getUsername()) {
            return false;
        }
    
        if ($this->password !== $user->getPassword()) {
            return false;
        }
    
        return true;
    }
    

    After doing this, the user is successfully authenticated.

    If above fix doesn't work, ensure that the data is properly validated. E.g:

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=40, unique=true)
     */
    private $username;
    

    and then generating a username with more than 40 characters will still give the same problem.

    打赏 评论

相关推荐 更多相似问题