API Platform GraphQL Security in Relationships

The security attribute allows to define roles or permissions necessary to execute a given query. However, it doesn’t define which relation available trough this query the user can access. To do so, you can use dynamic serialization groups.

Basically, mark the properties requiring a special role to be returned in the response with a specific serialization group, such as @Groups("admin"), then create a dynamic serialization context builder to add the special group if the connected user has this special role:


namespace App\Serializer;

use ApiPlatform\Core\GraphQl\Serializer\SerializerContextBuilderInterface;
use App\Entity\Book;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class BookContextBuilder implements SerializerContextBuilderInterface
    private $decorated;
    private $authorizationChecker;

    public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker)
        $this->decorated = $decorated;
        $this->authorizationChecker = $authorizationChecker;

    public function create(?string $resourceClass, string $operationName, array $resolverContext, bool $normalization): array
        $context = $this->decorated->create($resourceClass, $operationName, $resolverContext, $normalization);
        $resourceClass = $context['resource_class'] ?? null;

        if ($resourceClass === Book::class && isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && false === $normalization) {
            $context['groups'][] = 'admin';

        return $context;

In the master version (API Platform 2.6), the security attribute is now also available for properties. Unfortunately, this feature is currently available only in the REST subsystem, but we will be very pleased to merge a Pull Request adding support for this attribute to the GraphQL subsystem.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top