Authenticate multiple symfony2 firewalls with one login form

8.1k views Asked by At

I have two firewalls:

  1. api (for API calls)
  2. main (for everything else)

My client app login happens via the main firewall. However, it does interact with endpoints under the api firewall to fetch data. The problem here is that I don't want to force the user to log in a second time for authenticating against the second firewall.

How can I authenticate against both firewalls with just a single login form?

1

There are 1 answers

4
jstephenson On BEST ANSWER

Perhaps you could try the 'context' firewall property.

Say you have a configuration something like this (which presumably you do):

security:
    // providers etc ...

    firewall:
        main:
            pattern: # ...
            provider: my_users
            http_basic: ~
        api:
            pattern: # ...
            provider: my_users
            http_basic: ~

In this case the user's session will contain a '_security_main' property after authenticating against the 'main' firewall, and then when they attempt to access an 'api' location they will be prompted to re-auth and will then gain a '_security_api' session property.

To prevent this re-prompt, you can add the 'context' property to each firewall definition you wish to share the same authentication - so:

security:
    # providers etc ...

    firewall:
        main:
            pattern: # ...
            provider: my_users
            http_basic: ~
            context: primary_auth  # new
        api:
            pattern: # ...
            provider: my_users
            http_basic: ~
            context: primary_auth  # new

In this case, upon authentication with the 'main' firewall, a '_security_primary_auth' property will be set in the user's session. Any subsequent requests inside the 'api' firewill will then use the value of '_security_primary_auth' to establish authentication status (and so the user will appear authenticated).

Of course this authentication context sharing will work both ways around (whether they auth first with the 'main' or the 'api' firewall) - if you only wanted transience in one direction, things would be more complex.

Hope this helps.