Bambou
Bambou

Reputation: 1077

Allow post method only when user is not connected in API Platform

I've got an issue on my API. I'm working with API Platform and I'm pretty new with it so sorry in advance if my question might be silly.

In my API, I've got an administrator, a moderator and some users. What I want is that only a visitor can create accounts for users. So administrator, moderator and user can't create user accounts.

Here's my Hierarchy file (security.yaml) :

role_hierarchy:
    ROLE_MODERATOR: ROLE_USER
    ROLE_ADMIN: ROLE_MODERATOR

Here's the @ApiResource of my Entity User :

 * @ApiResource(
 *     attributes={
 *         "normalization_context"={"groups"={"read-user"}},
 *         "denormalization_context"={"groups"={"write-user"}},
 *         "validation_groups"=App\Validator\ValidationGroupsGenerator::class
 *     },
 *     collectionOperations={
 *         "get"={"method"="GET", "access_control"="is_granted('ROLE_MODERATOR')"},
 *         "post"={"method"="POST"}
 *     },
 *     itemOperations={
 *         "get"={"method"="GET", "access_control"="user.getId() === object.getId() or is_granted('ROLE_MODERATOR')"},
 *         "put"={"method"="PUT", "access_control"="user.getId() === object.getId() or is_granted('ROLE_MODERATOR')"}
 *     }
 * )

Here's my access_control (security.yaml) :

access_control:
    - { path: ^/users, role: IS_AUTHENTICATED_ANONYMOUSLY, methods: [POST] }

Scenario : I'm trying to create a user account as visitor / user / moderator / admin

My error : Moderator, admin and user can create user account

Expected result : Only a visitor can create a user account

What I've tried :

I add this in my entity

"post"={"method"="POST", "access_control"="user is null"}

It don't allow the roles to create a user account (gives a 403 Forbidden for them, which is what I want) but I've got a 401 JWT Token not found when trying to create an account as visitor now.

Do you have any solution to help me ? Thanks in advance

Upvotes: 1

Views: 756

Answers (1)

Bambou
Bambou

Reputation: 1077

Resolved by putting this in collectionOperations in my Entity User :

"post"={"method"="POST", "access_control"="is_granted('IS_AUTHENTICATED_FULLY') === false"}

Upvotes: 3

Related Questions