Search code examples
symfony5symfony-security

Symfony 5: Auth Multiple Guards and Different Providers


I am struggling with Symfony's guard authentication system for an API, it seems impossible to get it to work how I need.

Is it possible to use multiple authenticators AND different providers?

I need the flexibility so that users can potentially be authenticated in two ways for the same endpoints.

My firewall is currently:

        api:
          pattern: ^/
          stateless: true
          provider: jwt
          guard:
              authenticators:
                  - App\Security\InviteCodeAuthenticator
                  - lexik_jwt_authentication.jwt_token_authenticator
              entry_point: App\Security\InviteCodeAuthenticator

The JWT and invite code need totally different user providers. If I create a different firewall for each, then I have the same URLs protected by different firewalls and I need it to use either.

I am pulling hair out trying to get this to work now, I feel I am missing something obvious.


Solution

  • For anyone else who may encounter this, I had to use Symfony's new experimental authentication system to get this working:

    https://symfony.com/doc/current/security/experimental_authenticators.html#authenticators-removed-anonymous

    Then using a hybrid firewall:

            api:
              pattern: ^/
              stateless: true
              provider: jwt
              entry_point: App\Security\InviteCodeAuthenticator
              custom_authenticators:
                      - App\Security\InviteCodeAuthenticator
              guard:
                authenticators:
                      - lexik_jwt_authentication.jwt_token_authenticator
    

    This allowed my invite code authenitcator to inspect the request for a valid invite code and allow authentication or failign that fall back to expect a JWT.