0
votes

I am developing and application in symfony, with a pulic access where users logs in with a login form and an admin section with another login form and another user provider.

I've created a LoginFormAuthenticator for each area, and two firewalls to select the correct authenticator in each area. This is my security.yaml:

security: providers: admin_provider: entity: class: App\Entity\AdminUser property: email web_provider: entity: class: App\Entity\User property: email

firewalls:
    admin:
        pattern: '^/admin'
        anonymous: true
        provider: admin_provider
        guard:
            authenticators:
                - App\Security\AdminLoginFormAuthenticator
        logout:
            path: /admin/logout
            target: /
    main:
        anonymous: true
        provider: web_provider
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
        logout:
            path: /logout

Now I am adding an /api to the project, and both users should be able to access, managing the access rights diferently if the user is a public user or is an admin user.

When developing a controller in the /api area, I am unable to get the user when logged via the admin.

The question is, How in /api I can get the AdminUser if it is logged in or the User (in this order) when accessing $this->getuser() or $this->denyAccessUnlessGranted() ?

I've tried to add the App\Security\AdminLoginFormAuthenticator in main firewall and add a chain_provider in main.provider. But it is not working.

Thank you.

1

1 Answers

0
votes

The firewalls should share a "common context", for being able to access the same connected users. I think that wording comes from Symfony 2, where the SecurityContext was the service storing the user & authorization.

You need to modify slightly your configuration, and then $this->getUser() and $this->denyAccessUnlessGranted() will return/use the same User object for both firewalls.

firewalls:
    admin:
        pattern: '^/admin'
        context: my_app_context
        anonymous: true
        # ...
    main:
        anonymous: true
        context: my_app_context
        # ...

No need for a common provider or a custom guard. Though it may be easier to have the same User class everywhere, or at least common role for clarity.