Seb
Seb

Reputation: 330

Symfony2 optional stateless authentication

I have an API where I authenticate users thanks to a key that they send in each HTTP request. My firewall config is then something like:

firewalls:        
  authentication_required:
    stateless: true
    simple_preauth:
      authenticator: my_authenticator
    provider: my_provider

For some URLs I allow anonymous users, bypassing the authentication using security: false in the firewall config. It looks like:

firewalls:        
  authentication_not_required:
    stateless: true
    security: false

Now, I would like some URLs accessible for anonymous users, but keeping the possibility to be authenticated for existing users. The firewall config would look something like that but obviously it doesn't work:

firewalls:        
  my_area:
    stateless: true
    security: false
    simple_preauth:
      authenticator: my_authenticator
    provider: my_provider

Do someone has an idea about how to do it ?

Upvotes: 1

Views: 1201

Answers (2)

Seb
Seb

Reputation: 330

The solution was to add anonymous: ~ as suggested by Paweł Mikołajczuk, and to modify the authenticator to bypass it when necessary, as described here in the symfony Cookbook : http://symfony.com/doc/current/cookbook/security/api_key_authentication.html#only-authenticating-for-certain-urls

In my case, I pass an array of allowed anonymous paths to the ApiKeyAuthenticator service, and then at the beginin of its createToken() function, I check if the current path is or not allowed for anonymous access.

It looks something like:

// Allow some specific paths to have both anonymous and authenticated users
if (!$request->headers->has('X-Api-Key')) {
    foreach ($this->allowedAnonymousPaths as $path) {
        if ($this->httpUtils->checkRequestPath($request, $path)) {
            return;
        }
    }
}

Upvotes: 1

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3822

anonymous: ~ is your thing.

firewalls:        
    my_area:
        stateless: true
        anonymous: ~
        simple_preauth:
            authenticator: my_authenticator
        provider: my_provider

Upvotes: 2

Related Questions