v2.4 Security

Security

If you have yet to set up authentication for your API, refer to the section on JWT authentication.

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 control directives.

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

Here is an example:

<?php
// api/src/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",
 *         "post"={"access_control"="is_granted('ROLE_ADMIN')"}
 *     },
 *     itemOperations={
 *         "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user"},
 *         "put"={"access_control"="is_granted('ROLE_USER') and previous_object.owner == user"},
 *     }
 * )
 * @ORM\Entity
 */
class Book
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @var User The owner
     *
     * @ORM\ManyToOne(targetEntity=User::class)
     */
    public $owner;

    // ...
}

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

Additionally, in some cases you need to perform security checks on the original data. For example here, only the actual owner should be allowed to edit their book. In these cases, you can use the previous_object variable which contains the object that was read from the data provider.

N.B previous_object is cloned from the original object. Note that this clone is not a deep one (it doesn’t clone relationships, relationships are references), to make a deep clone implement __clone method in the concerned resource class.

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

# Configuring the Access Control Message

By default when API requests are denied, you will get the “Access Denied” message. You can change it by configuring the “access_control_message” attribute.

For example:

<?php
// api/src/Entity/Book.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;

/**
 * ...
 * @ApiResource(
 *     attributes={"access_control"="is_granted('ROLE_USER')"},
 *     collectionOperations={
 *         "post"={"access_control"="is_granted('ROLE_ADMIN')", "access_control_message"="Only admins can add books."}
 *     },
 *     itemOperations={
 *         "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user", "access_control_message"="Sorry, but you are not the book owner."}
 *     }
 * )
 */
class Book
{
    // ...
}

Alternatively, using YAML:

# api/config/api_platform/resources.yaml
App\Entity\Book:
    attributes:
        access_control: 'is_granted("ROLE_USER")'
    collectionOperations:
        post:
            method: 'POST'
            access_control: 'is_granted("ROLE_ADMIN")'
            access_control_message: 'Only admins can add books.'
    itemOperations:
        get:
            method: 'GET'
            access_control: 'is_granted("ROLE_USER") and object.owner == user'
            access_control_message: 'Sorry, but you are not the book owner.'
    # ...

In access control expressions for collections, the object variable contains the list of resources that will be serialized. To remove entries from a collection, you should implement a Doctrine extension to customize the generated DQL query (e.g. add WHERE clauses depending of the currently connected user) instead of using access control expressions.

If you use custom data providers, you’ll have to implement the filtering logic according to the persistence layer you rely on.

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