Search code examples
symfonyfirewallsymfony-security

Symfony 4 : How to have multi providers for user/admin in firewall?


I can not have two different providers for user and admin with two different forms

I want to have two firewalls, for users and for admins. I created two different providers linking two different entities. I can log in as a user, but never as Admin .. I do not understand what I need to add more.

Another thing, I know that there is app.user. But is there also app.admin? In order to have two completely separate accounts on two different firewalls?

security:
providers:
    user_provider:
        entity:
            class: App\Entity\User
            property: username
    admin_provider:
        entity:
            class: App\Entity\Admin
            property: username
    chain_provider:
        chain:
            providers: [user_provider, admin_provider]
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        pattern: ^/
        provider: user_provider
        anonymous: true
        logout:
            path: /logout
            target: /login
        remember_me:
            secret:   '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path:     /
        form_login:
            login_path: /login
            check_path: /login
    backoffice:
        pattern: ^/backoffice
        provider: admin_provider
        logout:
            path: /backoffice/logout
            target: /backoffice/login
        form_login:
            login_path: /backoffice/login
            check_path: /backoffice/login
access_control:
    - { path: ^/backoffice/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/backoffice, roles: ROLE_ADMIN }
    - { path: ^/mon-compte, roles: ROLE_USER }
encoders:
    App\Entity\User:
        algorithm: bcrypt
        cost: 12
    App\Entity\Admin:
        algorithm: bcrypt
        cost: 12

I have null error when I call $authenticationUtils->getLastAuthenticationError()


Solution

  • Switch firewalls order, so the main firewall is the last one.

    Symfony uses only one firewall per request and it's the first matched with the pattern. So in your case it's using main firewall for ^/backoffice urls too because /backoffice matches ^/ pattern.

    I'm not sure if it will solve all your issues here, but you need to do this in order to really use backoffice firewall.

    Regarding app.user and app.admin - no, there's no app.admin. Admin is a user too, so when you'll be logged in as admin, you'll get its entity with app.user