简体   繁体   English

Symfony 5 - 在身份验证时动态设置角色

[英]Symfony 5 - Dynamically set roles on authentication

In Symfony, during the authentification, i want to attribute specific role to my user.在 Symfony 中,在身份验证期间,我想将特定角色归因于我的用户。

If i specify ->setRoles() in my authenticator, or my "getRoles" function, i come back to the login page, anonymously如果我在身份验证器或“getRoles”function 中指定->setRoles() ,我会匿名返回登录页面

Following code in Authenticator doesn't work Authenticator 中的以下代码不起作用

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(['customId' => $credentials['customId']]);

    if (!$user) {
        // fail authentication with a custom error
        throw new CustomUserMessageAuthenticationException('CustomId could not be found.');
    }
    if($user->getId() == 2) {
        $user->setRoles(['ROLE_SUPER_ADMIN']);
    }
    return $user;
}

This code in my Entity doesn't work我的实体中的此代码不起作用

/**
 * @see UserInterface
 */
public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = 'ROLE_USER';
    if($this->getId() == 2) {
        $this->setRoles(['ROLE_SUPER_ADMIN']);
    }
    return array_unique($roles);
}

Could you help me?你可以帮帮我吗? Thxs谢谢

If you change the user object it will not match the one in the database.如果您更改用户 object,它将与数据库中的用户不匹配。 Symfony will recognize this as someone messing with the stored data and log you out for safety. Symfony 会将此识别为有人在弄乱存储的数据,并出于安全考虑将您注销。

You can change how the comparison of the user is done by implementing the EquatableInterface:您可以通过实现 EquatableInterface 来更改用户比较的方式:

class User implements EquatableInterface
{
    public function isEqual(UserInterface $user): bool
    {
        // Example for what your comparison could look like
        return $user->getUsername() === $this->getUsername() && $user->getId() === $this->getId();
    }
}

You can find this (in a rather small section) in the docs: https://symfony.com/doc/current/security/user_provider.html#comparing-users-manually-with-equatableinterface您可以在文档中找到这个(在一个相当小的部分): https://symfony.com/doc/current/security/user_provider.html#comparing-users-manually-with-equatableinterface

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM