bought777 bought777 - 6 months ago 197
PHP Question

Symfony2 redirect /admin/* to /admin/login when not logged in (or use FOSUserBundle?)

I am new to Symfony and I am trying to build an admin interface. I have an existing users table and all I want is to secure the

^/admin.+
path with a login page at
/admin/login
and Symfony seems to be very tutorial-oriented with little explanation on how to customize anything. (or at least, not much info on how each piece component works together with the others)

Here is my security.yml

encoders:
AppBundle\Entity\Users:
algorithm: sha1
encode_as_base64: false
iterations: 1

role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]

providers:
administrators:
entity: { class: AppBundle:Users, property: email }
in_memory:
memory: ~

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

main:
anonymous: ~

admin_area:
pattern: ^/admin
anonymous: ~
provider: administrators
form_login:
default_target_path: /admin
check_path: /admin/login_check
login_path: /admin/login
remember_me: true
logout:
path: /admin/logout
target: /admin

access_control:
- { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, roles: ROLE_ADMIN }


When I go to /admin I get error page with "Full authentication is required to access this resource." What I want is for the app to redirect from
/admin/*
(except /admin/login of course) to
/admin/login
when not logged in.

Notes & Other Questions

Symfony seems to want you to always use certain existing bundles and I have scoured the web for info on how to understand what's actually happening but only seem to find more and more tutorials.

Should I even be using FOSUserBundle? If so, can I use my existing users table or do I have to use their schema?

Answer

You should change the order of firewalls, so make admin_area before main

admin_area:
    pattern:    ^/admin
    anonymous:  ~
    provider:   administrators
    form_login:
        default_target_path: /admin
        check_path: /admin/login_check
        login_path: /admin/login
        remember_me: true
    logout:
        path:   /admin/logout
        target: /admin

main:
    anonymous: ~

Explication

In our example, the main firewall doesn't contain pattern, then if it's defined in first order it will take all routes. so in this firewall (main) we don't define the form_login then we get the error page with "Full authentication is required to access this resource.".

In another way, if you add the pattern in the main firewall, you will not have the error (see the example above)

main:
    pattern: /home
    anonymous: ~
admin_area:
    pattern:    ^/admin
    anonymous:  ~
    provider:   administrators
    form_login:
        default_target_path: /admin
        check_path: /admin/login_check
        login_path: /admin/login
        remember_me: true
    logout:
        path:   /admin/logout
        target: /admin
Comments