Grapic dots

API Platform: Dynamically Restrict Properties Based on User

Mike Milano

When developing an API which has users with different roles accessing the data, there’s often properties which should only be accessible to privileged users.

I’ve written about how to restrict properties, by adding serialization groups to each property, but now we need to set the serialization context based on the current user.

Our API

To explain this, let me define some details about the API we will discuss: - There is a Comment resource available for anyone to retrieve. - The Comment resource includes id, name, email, and other fields which we’re not concerned about here. - Everyone can see the id name properties - Only administrators can see the email property.

Of course a comment would typically have a message and relation to an entity the comment is associated with, but all I want to explain here is how to make email available to administrators, and no one else.

Here is the relevant code for the Comment entity:

  1. <?php
  2. // api/src/Entity/Comment.php
  3.  
  4. namespace App\Entity;
  5.  
  6. use ApiPlatform\Core\Annotation\ApiResource;
  7. use Symfony\Component\Serializer\Annotation\Groups;
  8.  
  9. /**
  10.   * @ApiResource(
  11.   * normalizationContext={"groups"={"read"}},
  12.   * denormalizationContext={"groups"={"write"}}
  13.   * )
  14.   */
  15. class Comment
  16. {
  17. /**
  18.   * @Groups({"read"})
  19.   */
  20. private $id;
  21.  
  22. /**
  23.   * @Groups({"read"})
  24.   */
  25. private $name;
  26.  
  27. /**
  28.   *
  29.   */
  30. private $email;
  31.  
  32. // ...
  33. }
  34. ...

Notice we’ve provided the default serialization contexts in the ApiResource() definition.

This means:

  • For normalization requests (GET), the read context is applied.
    • Any property defined with the read group will be included with the results.
  • For denormalization requests (POST/PUT/etc.), the ‘write’ context is applied.
    • Any property defined with the write group can be added/updated.

I’ll focus on the read context and group for the sake of simplicity.

Our objective at this point is to make the email property available to administrators.

The Solution

Fortnately, API Platform provides a way to change the serialization context dynamically.

To make the email property available to administrators, we need to: - Add an admin:read serialization group to the email property. - Apply the admin:read context when an administrator is making the request.

First, let’s update the entity.

  1. <?php
  2. // src/Entity/Comment.php
  3. namespace App\Entity;
  4.  
  5. use ApiPlatform\Core\Annotation\ApiResource;
  6. use Symfony\Component\Serializer\Annotation\Groups;
  7.  
  8. /**
  9.  * @ApiResource(
  10.  * normalizationContext={"groups"={"read"}},
  11.  * denormalizationContext={"groups"={"write"}}
  12.  * )
  13.  */
  14. class Comment
  15. {
  16. /**
  17.   * @Groups({"read"})
  18.   */
  19. private $id;
  20.  
  21. /**
  22.   * @Groups({"read"})
  23.   */
  24. private $name;
  25.  
  26. /**
  27.   * @Groups({"admin:read"})
  28.   */
  29. private $email;
  30.  
  31. // ...
  32. }
  33. ...

At this point, there is no change in the results a user will receive. We’ve defined the admin:read group on the email property, but read and write are the only contexts available by default.

What is required now is to create a context builder and expose it as a service.

Consider createFromRequest() carefully to see how we’re adding admin:read and admin:write.

Note: We could target the Comment resource by analyzing $context in createFromRequest(), however I have opted to make admin:read and admin:write available to all resources if the current user is an administrator.

  1. <?php
  2. // src/Serializer/AdminContextBuilder.php
  3. namespace App\Serializer;
  4.  
  5. use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  8.  
  9. final class AdminContextBuilder implements SerializerContextBuilderInterface
  10. {
  11. private $decorated;
  12. private $authorizationChecker;
  13.  
  14. public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker)
  15. {
  16. $this->decorated = $decorated;
  17. $this->authorizationChecker = $authorizationChecker;
  18. }
  19.  
  20. public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
  21. {
  22. $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
  23. // Add `admin:read` for normalization requests
  24. // Otherwise, add `admin:write` for denormalization requests
  25. if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
  26. $context['groups'][] = $normalization ? 'admin:read' : 'admin:write';
  27. }
  28.  
  29. return $context;
  30. }
  31. }

Now define the service in config/services.yaml

...
    'App\Serializer\AdminContextBuilder':
        decorates: 'api_platform.serializer.context_builder'
        arguments: [ '@App\Serializer\AdminContextBuilder.inner' ]
        autoconfigure: false

… and that’s it. Now when a user with ROLE_ADMIN makes a request, admin:read group will be added and any property with that group defined will be made available.

8 Reasons Why Standardizing on Drupal is the Right Choice for Enterprise.
Read about it in this free white paper.

Download for Free Now!