v2.1 Security


To completely disable some operations from your application, refer to the disabling operations section.

Using API Platform, you can leverage all security features provided by the Symfony Security component. For instance, if you wish to restrict the access of some endpoints, you can use access controls directives.

Since 2.1, you can add security through Symfony’s access control expressions in your entities.

Here is an example:

// src/AppBundle/Entity/Book.php

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

 * Secured resource.
 * @ApiResource(
 *     attributes={"access_control"="is_granted('ROLE_USER')"},
 *     collectionOperations={
 *         "get"={"method"="GET"},
 *         "post"={"method"="POST", "access_control"="is_granted('ROLE_ADMIN')"}
 *     },
 *     itemOperations={
 *         "get"={"method"="GET", "access_control"="is_granted('ROLE_USER') and object.owner == user"}
 *     }
 * )
 * @ORM\Entity
class Book
     * @var int
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
    public $id;

     * @var string The title
     * @ORM\Column
     * @Assert\NotBlank
    public $title;

     * @ORM\Column
    public $owner;

This example is going to allow only fetching the book related to the current user. If he tries to fetch a book which is not linked to his account, that will not return the resource. In addition, only admins are able to create books which means that a user could not create a book.

It is also possible to use the event system for more advanced logic or even custom actions if you really need to.

You can also help us improve the documentation of this page.

Made with love by

Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.

Learn more

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop