Symfony access control with variable inside route

George Irimiciuc picture George Irimiciuc · Jan 18, 2016 · Viewed 8k times · Source

I'm defining security for my website in security.yml

    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/ad/new, role: ROLE_USER  }
    - { path: ^/myAds, role: ROLE_USER  }
    - { path: ^/payments, role: ROLE_USER  }
    - { path: ^/pay, role: ROLE_USER  }

But I'm not sure how such a route would be added here:

mybundle_contact_advertiser:
   path:    /ad/{id}/contact
   defaults:   { _controller: MyBundle:Default:contactAdvertiser,id:null}

How is the id defined, considering I can't do it like so:

    - { path: ^/ad, role: ROLE_USER  }

As a route like

mybundle_ad:
    path:      /ad/{id}
    defaults:  { _controller: MyBundle:Default:viewAd ,id:null}

Would not work for unregistered users.

Answer

Daishi picture Daishi · Mar 21, 2017

All answers from @turdaliev-nursultan work.

But if you know that the {id} parameter will always be an integer, there's an additional possible answer.

You can edit the security.yml file and add the following rule to the access_control list :

- { path: ^/ad/[0-9]+/contact$, role: ROLE_USER }

The [0-9]+ part means any string made of one or more digits from 0 to 9.

Keep also in mind that using any url like http://example.com/ad/foo/contact, where the parameter is not an existing id, will lead to an http 404 error.