Home » Php » php – How do I require authentication for POST requests but allow unathenticated use for GET requests on my token-secured API?

php – How do I require authentication for POST requests but allow unathenticated use for GET requests on my token-secured API?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have REST API and I want a certain route on which requests are GET to be public, but I want POST request to require a token.

Example:

// config/packages/security.yaml

security:
    # ...
    firewalls:
        api:
            pattern: ^/api/v1/
            // here I want to allow public GET
            // but want to disallow POST without a token
            guard:
                authenticators:
                    - App\Security\TokenAuthenticator

I have a standard TokenAuthenticator class, in charge of authenticating users.

How can I configure Symfony security so that POST requests require authorization, but GET requests can be performed by unauthenticated (anonymous) users?

How to&Answers:

This can be very succinctly achieved with access control rules:

E.g.:

access_control:
        - { path: ^/api/v1, roles: IS_AUTHENTICATED_ANONYMOUSLY, methods: [GET] }
        - { path: ^/api/v1, roles: ROLE_ADMIN, methods: [POST] }

With this, POST requests to api/v1 will require the user to have been authenticated and ave a ROLE_ADMIN assigned, but GET requests to the same path will be allowed for unauthenticated users.