Redirect to "/login" if is not logged in

ReynierPM picture ReynierPM · Jul 15, 2014 · Viewed 10.9k times · Source

I need to redirect everyone to route /login if:

  • Access to / route (app.php or app_dev.php)
  • Try to access any restricted area and the client belongs to group or have the right credentials but it's not logged in (not so sure this will be necessary since maybe Symfony handle this part)

So I did this in my security.yml:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        main:
            pattern: ^/
            anonymous: ~
            form_login:
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
            logout:       true

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

And this in routing.yml:

common:
    resource: "@CommonBundle/Controller/"
    type:     annotation
    options:
        expose: true

user:
    resource: "@UserBundle/Controller/"
    type:     annotation
    options:
        expose: true

# FOSUserBundle Routes
fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile

fos_user_group:
    resource: "@FOSUserBundle/Resources/config/routing/group.xml"
    prefix: /group

#FOSJsRouting
fos_js_routing:
    resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml"

Any time I access app_dev.php I go to CommonController.php at indexAction() and don't redirect to login, what I miss?

Answer

Alex picture Alex · Jul 15, 2014

You need to make the entire site closed off to non authenticated users by adding a rule to the access_control. However, ensure that /login is an exception to this rule, by putting the exception before it.

access_control:
- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, role: ROLE_USER }