Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 978
Adel 'Sean' Helal Avatar asked Sep 10 '15 23:09

Adel 'Sean' Helal


2 Answers

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 :)

like image 183
Adel 'Sean' Helal Avatar answered Oct 06 '22 22:10

Adel 'Sean' Helal


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
like image 39
10us Avatar answered Oct 06 '22 20:10

10us