简体   繁体   中英

Symfony 5 - Dynamically set roles on authentication

In Symfony, during the authentification, i want to attribute specific role to my user.

If i specify ->setRoles() in my authenticator, or my "getRoles" function, i come back to the login page, anonymously

Following code in Authenticator doesn't work

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. Symfony will recognize this as someone messing with the stored data and log you out for safety.

You can change how the comparison of the user is done by implementing the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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