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 ?

2 Answers2

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

  • 2
    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 **firewall** – Wojtek vanDer Feb 27 '20 at 09:56
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
10us
  • 1,622
  • 18
  • 13