Symfony2 - Secure specific HTTP methods for URL Symfony2 - Secure specific HTTP methods for URL symfony symfony

Symfony2 - Secure specific HTTP methods for URL


I know it is late, but if someone stumbles on this questions here is how to secure per a request per HTTP method (see the Symfony security documentation):

# app/config/security.ymlsecurity:    # ...    access_control:        - { path: ^/api/v1/users.json, roles: ROLE_ADMIN, methods: [POST, PUT] }        - { path: /api/v1/users.json, roles: ROLE_ADMIN }

Be careful the order in which you set the rules matters.


According to the security reference book, you can't secure a URL by method.

Not the best way but you can do like that, in the action:

public function listAction(Request $request){    if ($request->getMethod() == 'GET' && !$this->get('security.context')->isGranted('ROLE_ADMINISTRATOR')) {        throw $this->createNotFoundException("This page doesn't exist."); // forward a 404, or a message in a json...    }    return new Response('Cubilon\\SocialPortal\\APIBundle\\Controller\\UserController', 200);}

Or you can create a new kernel event listener that will check the method and the user ROLE like my previous example, but extend to all the actions ! ^^


Watch out, there are 2 things:

  • firewall (authentication)
  • access control (authorization)

The accepted answer shows how to restrict an access control rule to an HTTP method, but here is how to restrict a firewall rule to an HTTP method:

security:    firewalls:        secured_area:            methods: [POST, PUT]

Note that this feature was added in Symfony 2.5.

As shown in the other answer, here is how to restrict an access control rule to an HTTP method:

security:    # ...    access_control:        - { path: ^/api/v1/users.json, roles: ROLE_ADMIN, methods: [POST, PUT] }