Anh Nguyen
Anh Nguyen

Reputation: 192

How to prevent access to specific routes in Symfony 2

I'm new to symfony2 and I don't understand the way the security.yml works

I have 2 roles in my application: ROLE_USER, ROLE_ADMIN.

ROLE_USER: can only view (cannot CRUD)
ROLE_ADMIN: can do everything (can CRUD)

I have 2 basic questions:

  1. Is there only 1 security.yml in app/config? Can I create a security.yml for my bundle ThePartner\EZFBundle\Resource\config where I can specify which route a role can access?

  2. I want to prevent ROLE_USER to access to route blue_form_new, blue_form_create, blue_form_edit, blue_form_update, blue_form_delete? This ROLE_USER could only access blue_form, blue_form_show

Here is my ThePartner\EZFBundle\Resources\routing.yml

ThePartnerEZFBundle_blue_form:
    resource: "@ThePartnerEZFBundle/Resources/config/routing/blueform.yml"
    prefix:   /blue_form

Here is the ThePartnerEZFBundle/Resources/config/routing/blueform.yml

blue_form:
    pattern:  /
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:index" }

blue_form_show:
    pattern:  /{id}/show
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:show" }

blue_form_new:
    pattern:  /new
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:new" }

blue_form_create:
    pattern:  /create
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:create" }
    requirements: { _method: post }

blue_form_edit:
    pattern:  /{id}/edit
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:edit" }

blue_form_update:
    pattern:  /{id}/update
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:update" }
    requirements: { _method: post|put }

blue_form_delete:
    pattern:  /{id}/delete
    defaults: { _controller: "ThePartnerEZFBundle:BlueForm:delete" }
    requirements: { _method: post|delete }

Thanks guys

Upvotes: 1

Views: 2192

Answers (1)

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10890

All you need to configure is your security.yml. You can define multiple firewalls which will apply to different routes:

security:
    firewalls:
        your_first_firewall:
            pattern: /public/ #this is regexp, so all urls starting with /public/ will   match
            security: false #this will be public, no firewall
        your_second_firewall:
            pattern: /nonPublic/
            security: true

Remember that order of your firewall entries is important - first pattern matched will "win".

You can also import security settings from your bundle. To do that you need to import your bundle's security.yml file in main config.yml - described here)

# app/config/config.yml
imports:
    - { resource: '@AcmeDemoBundle/Resources/config/security.yml' }

Upvotes: 2

Related Questions