Wide abstract background featuring a cartoon spider performing a check on a stylized cloud network, relevant for content about API platform serialization checks and data validation.

API Platform: Advanced Security (Voters)

10/08/2023

When developing a rest API, it often happens that you want control over which users have the access to a specific resource. The usage of user roles can cover some cases. But what if you want to restrict the access not based on a given role, but some other dependencies? Sometimes the use cases you need to cover become quite complicated, other times they are simple, but repetitive. What allows you to control the access in a clean, un-repetitive way is called voters.

What Is a Voter?

Citing the Symfony docs, “Voters are Symfony's most powerful way of managing permissions. They allow you to centralize all permission logic, then reuse them in many places.”

What does it mean in practice? Voters are classes that extend the Symfony voter abstract class, and you can use them in order to enable access for the endpoint in the circumstances specified by you however you need it.

What Does a Voter Look Like?

class ShopVoter extends Voter
{
  protected function supports(string $attribute, mixed $subject): bool
  {
    ...
  }
  protected function voteOnAttribute(
    string $attribute,
    $subject,
    TokenInterface $token
  ): bool {
    ...
  }
}

In the provided example, we have created a voter that will be used to control access to the “Shop” resource.

The voter implementation needs to only implement two functions: supports and voteOnAttribute.

supports

This function needs to return true or false depending if we want to use this voter in the incoming request.

The most common usage of the voters is to create a Voter for each resource, and check whether the “$subject” is of the corresponding type, and if the attribute we are voting on is handled:

public const CREATE = 'create';
public const READ = 'read';

private const SUPPORTED_ATTRIBUTES = [
  self::CREATE,
  self::READ,
];

protected function supports(string $attribute, mixed $subject): bool
{
  return
    $subject instanceof Shop &&
    in_array($attribute, self::SUPPORTED_ATTRIBUTES)
  ;
}

Of course this logic can be modified to match your needs.

voteOnAttribute

Function voteOnAttribute is responsible for finding out if we want to enable access to the given resource based on the attribute, the subject and a $token implementing Symfony’s TokenInterface that is given to us based on the configured authentication.

protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
  /** @var User|null|string $user */
  $user = $token->getUser();
  if (!$user instanceof User) {
    return false;
  }
  switch ($attribute) {
    case self::CREATE:
      return $this->authorizationChecker->isGranted('ROLE_ADMIN');
    case self::READ:
      return $this->shopService->isUserAShopManager($user, $subject);
  }
  return false;
}

What’s really handy is that you can use dependency injection in order to use other services inside of your voter as shown above! In the default configuration, it’s enough to just add the required services to the voter’s “__construct” method.

How to Use the Custom Voter in API Platform?

The only thing you need to do is to add a “security” to your endpoint definition. You can use Is_granted by providing the “attribute” as the first argument, and the resource object as the second argument:

App\Entity\Shop:
  itemOperations:
    get:
      security: is_granted('read', object)
    post:
      security: is_granted('create', object)
Łu
Portret Łukasza Traczyka, back-end developera w Primotly, profesjonalisty o swobodnym i przystępnym usposobieniu, ubranego w jasnoniebieską koszulę.
Łukasz Traczyk
Back-end Developer

Najnowsze artykuły

Ilustracja do artykułu o NLP (przetwarzaniu języka naturalnego)

Development | 11/10/2024

Czym jest przetwarzanie języka naturalnego (NLP)?

Łukasz Kopaczewski

Rozwiązania NLP stają się coraz bardziej popularne, ponieważ sztuczna inteligencja ewoluuje i znajduje zastosowania w różnych branżach. Od przekształcania obsługi klienta w sklepach internetowych dzięki natychmiastowym odpowiedziom po zapewnianie dokładnych tłumaczeń językowych, NLP zmienia zasady gry w wielu obszarach.

Szczegóły
Obrazek nawiązujący do aspektów ESG i etyki AI.

Innovations | 09/10/2024

Etyka AI w ESG - Odpowiedzialna innowacja

Bernhard Huber

Połączenie sztucznej inteligencji i strategii ESG stwarza zarówno możliwości, jak i dylematy etyczne. Z jednej strony sztuczna inteligencja może być potężnym narzędziem do realizacji celów zrównoważonego rozwoju, optymalizacji wykorzystania zasobów i wspierania odpowiedzialnych praktyk biznesowych.

Szczegóły
Podgląd pojedynczego artykułu

Innovations | 03/10/2024

Chatbot AI - wirtualny asystent do zautomatyzowanej obsługi klienta

Agata Pater

Posiadanie asystenta opartego na sztucznej inteligencji stało się naturalną częścią naszego codziennego życia - od sterowania urządzeniami domowymi i robienia zakupów po zarządzanie naszymi finansami. Szybko się do nich przyzwyczailiśmy, ponieważ używają naturalnego języka, są intuicyjne w obsłudze i wspierają nasze codzienne zadania z niezwykłą dokładnością. Ale jak dokładnie działają i jak możemy w pełni wykorzystać ich potencjał?

Szczegóły