ApiPlatform and my security go-tos

Spread the love

There are 4 security go-tos I use in my ApiPlatform projects. I’ll describe them below

Use only needed endpoints

Entities will automatically make all the usual endpoints. But sometimes thats a bit too much. Take a look at https://symfonycasts.com/screencast/api-platform/operations and see how you can get rid of the points you won’t use. Don’t want to ever delete from a DB? Take it out from your item operations, now if someone tries system will stop it.

is_granted

I heavily use the is_granted method. In fact, although I know its from Symfony, it was reading that in ApiPlatform docs that got me the first time. Its a way of quickly visualizing for me what I allow and for who. Yes, its not enough, but its a start.

* collectionOperations={
*         "get"={"security"="is_granted('ROLE_ADMIN')"}
* }

object.

You can use the “object” to match something to the current model. For example:

object.getId()==user.getTeam().getId()

The above on Team entity will make sure the logged in user has the same team ID as the team I am trying to edit/view or wherever I have that check.

Controller

Sometimes you need a bit more logic. For example, although I am sure there is a more elegant way, I had not found a better way to automatically inject the Team to my entity. So… I use a custom controller on a “regular” endpoint. This involves the annotation in collectionOperations:

*          "post"={
*               "method"="GET",
*              "controller"=DashboardGetCollectionController::class,
*          }

And the controller itself. These controllers must have an __invoke method. Here is a sample

public function __invoke(UserInterface $user, EntityManagerInterface $em): array
{
if ($user instanceof User) {
return $em->getRepository(Dashboard::class)->findBy(['owner' => $user]);
}

return [];
}

Although I use a similar method for other ways of scoping data…