Home > Software design >  How to make a single endpoint operation public in API Platform?
How to make a single endpoint operation public in API Platform?

Time:11-05

In API Platform, I have all the endpoints secured with JWT but I would like to have the POST User public so users can register themselves.

How can I do this at entity level?

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ApiResource(
    collectionOperations: [
        'get',
        "post" => ["security" => "is_granted('PUBLIC_ACCESS')"], //this does not work
    ],
    itemOperations: [
        'get'
    ],
)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{

if I implement this in security.yaml as usual in Symfony it works

access_control:
        - { path: ^/docs, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI
        - { path: ^/authentication_token, roles: PUBLIC_ACCESS }
        - { path: ^/users, roles: PUBLIC_ACCESS, methods: POST }
        - { path: ^/, roles: IS_AUTHENTICATED_FULLY }

I just would like to know if I can do it at entity level with annotations.

CodePudding user response:

The Api-Platform security rules are processed after Symfony's Security access rules.

So if Symfony's access rules are stricter than Api-Platform's rules, those apply and the request will be denied.

If if were the other way around (security.access_rules declared the endpoint "open", but on your resource configuration you declared a more stringent is_granted() configuration), it would work, since then request would go past the Symfony firewall and reach the Api-Platform access listener.

For you to be able to configure security with attributes/annotations, then the security configuration needs to be more restrictive than the one on the Symfony firewall.

E.g. set / to PUBLIC_ACCESS, and then configure security with the corresponding is_granted() on each resource.

  • Related