簡體   English   中英

Symfony 5 - 在身份驗證時動態設置角色

[英]Symfony 5 - Dynamically set roles on authentication

在 Symfony 中,在身份驗證期間,我想將特定角色歸因於我的用戶。

如果我在身份驗證器或“getRoles”function 中指定->setRoles() ,我會匿名返回登錄頁面

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;
}

我的實體中的此代碼不起作用

/**
 * @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);
}

你可以幫幫我嗎? 謝謝

如果您更改用戶 object,它將與數據庫中的用戶不匹配。 Symfony 會將此識別為有人在弄亂存儲的數據,並出於安全考慮將您注銷。

您可以通過實現 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();
    }
}

您可以在文檔中找到這個(在一個相當小的部分): 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