How to exclude an api route from symfony2 firewall based on method
Asked Answered
Y

2

5

So i am building a symfony2 api using fosrestbundle fosuserbundle and LexikJWTAuthenticationBundle and when i want to acces to /api/users.json to post a new user i get a 401 error Bad Credentials.

i tried to add a line in access control this way :

- { path: post_user, role: IS_AUTHENTICATED_ANONYMOUSLY }   

but it didn't work.

i also tried :

- { path: post_user, role: IS_AUTHENTICATED_ANONYMOUSLY, methods:[POST] }   

how can i exclude only the post endpoint ?

Yellowweed answered 10/9, 2015 at 23:51 Comment(0)
Y
9

The solution is to create a new firewall disabling authentication on a url pattern. The tricky thing is that security configuration also allows you to select the methods covered by the firewall.

Just add this in your firewalls in security.yml :

public:
            methods: [POST]
            pattern: ^/api/users
            security: false

you have now access to your endpoint on post method and get put and delete will still require whatever authentication protocol you use :)

Yellowweed answered 10/9, 2015 at 23:51 Comment(1)
One more thing -> if in your firewall section you have other rules like: 'main: http_basic: true' then your public rule should be at the top, just below firewallTroy
S
2

Do mind when using Adel's solution and using @Security Annotations in your controller or actions you get this exception :

The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

This can be circumvented by replacing security: false with anonymous : true. So the complete solution is :

public:
     methods: [POST]
     pattern: ^/api/users
     anonymous : true
Secondly answered 3/1, 2019 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.