Nowadays, it's quite usual to authenticate the user via an API key (when developing
a web service for instance). The API key is provided for every request and is
passed as a query string parameter or via an HTTP header.

// src/AppBundle/Security/ApiKeyAuthenticator.phpnamespaceAppBundle\Security;useSymfony\Component\HttpFoundation\Request;useSymfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;useSymfony\Component\Security\Core\Authentication\Token\TokenInterface;useSymfony\Component\Security\Core\Exception\AuthenticationException;useSymfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;useSymfony\Component\Security\Core\Exception\BadCredentialsException;useSymfony\Component\Security\Core\User\UserProviderInterface;useSymfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;classApiKeyAuthenticatorimplementsSimplePreAuthenticatorInterface{publicfunctioncreateToken(Request$request,$providerKey){// look for an apikey query parameter$apiKey=$request->query->get('apikey');// or if you want to use an "apikey" header, then do something like this:// $apiKey = $request->headers->get('apikey');if(!$apiKey){thrownewBadCredentialsException();// or to just skip api key authentication// return null;}returnnewPreAuthenticatedToken('anon.',$apiKey,$providerKey);}publicfunctionsupportsToken(TokenInterface$token,$providerKey){return$tokeninstanceofPreAuthenticatedToken&&$token->getProviderKey()===$providerKey;}publicfunctionauthenticateToken(TokenInterface$token,UserProviderInterface$userProvider,$providerKey){if(!$userProviderinstanceofApiKeyUserProvider){thrownew\InvalidArgumentException(sprintf('The user provider must be an instance of ApiKeyUserProvider (%s was given).',get_class($userProvider)));}$apiKey=$token->getCredentials();$username=$userProvider->getUsernameForApiKey($apiKey);if(!$username){// CAUTION: this message will be returned to the client// (so don't put any un-trusted messages / error strings here)thrownewCustomUserMessageAuthenticationException(sprintf('API Key "%s" does not exist.',$apiKey));}$user=$userProvider->loadUserByUsername($username);returnnewPreAuthenticatedToken($user,$apiKey,$providerKey,$user->getRoles());}}

Once you've configured everything,
you'll be able to authenticate by adding an apikey parameter to the query
string, like http://example.com/api/foo?apikey=37b51d194a7513e45b56f6524f2d51f2.

The authentication process has several steps, and your implementation will
probably differ:

Early in the request cycle, Symfony calls createToken(). Your job here
is to create a token object that contains all of the information from the
request that you need to authenticate the user (e.g. the apikey query
parameter). If that information is missing, throwing a
BadCredentialsException
will cause authentication to fail. You might want to return null instead
to just skip the authentication, so Symfony can fallback to another authentication
method, if any.

Caution

In case you return null from your createToken() method, be sure to enable
anonymous in you firewall. This way you'll be able to get an AnonymousToken.

After Symfony calls createToken(), it will then call supportsToken()
on your class (and any other authentication listeners) to figure out who should
handle the token. This is just a way to allow several authentication mechanisms
to be used for the same firewall (that way, you can for instance first try
to authenticate the user via a certificate or an API key and fall back to
a form login).

Mostly, you just need to make sure that this method returns true for a
token that has been created by createToken(). Your logic should probably
look exactly like this example.

If supportsToken() returns true, Symfony will now call authenticateToken().
One key part is the $userProvider, which is an external class that helps
you load information about the user. You'll learn more about this next.

In this specific example, the following things happen in authenticateToken():

First, you use the $userProvider to somehow look up the $username that
corresponds to the $apiKey;

Second, you use the $userProvider again to load or create a User
object for the $username;

Finally, you create an authenticated token (i.e. a token with at least one
role) that has the proper roles and the User object attached to it.

The goal is ultimately to use the $apiKey to find or create a User
object. How you do this (e.g. query a database) and the exact class for
your User object may vary. Those differences will be most obvious in your
user provider.

The $userProvider can be any user provider (see How to Create a custom User Provider).
In this example, the $apiKey is used to somehow find the username for
the user. This work is done in a getUsernameForApiKey() method, which
is created entirely custom for this use-case (i.e. this isn't a method that's
used by Symfony's core user provider system).

// src/AppBundle/Security/ApiKeyUserProvider.phpnamespaceAppBundle\Security;useSymfony\Component\Security\Core\User\UserProviderInterface;useSymfony\Component\Security\Core\User\User;useSymfony\Component\Security\Core\User\UserInterface;useSymfony\Component\Security\Core\Exception\UnsupportedUserException;classApiKeyUserProviderimplementsUserProviderInterface{publicfunctiongetUsernameForApiKey($apiKey){// Look up the username based on the token in the database, via// an API call, or do something entirely different$username=...;return$username;}publicfunctionloadUserByUsername($username){returnnewUser($username,null,// the roles for the user - you may choose to determine// these dynamically somehow based on the userarray('ROLE_API'));}publicfunctionrefreshUser(UserInterface$user){// this is used for storing authentication in the session// but in this example, the token is sent in each request,// so authentication can be stateless. Throwing this exception// is proper to make things statelessthrownewUnsupportedUserException();}publicfunctionsupportsClass($class){return'Symfony\Component\Security\Core\User\User'===$class;}}

The logic inside getUsernameForApiKey() is up to you. You may somehow transform
the API key (e.g. 37b51d) into a username (e.g. jondoe) by looking
up some information in a "token" database table.

The same is true for loadUserByUsername(). In this example, Symfony's core
User class is simply created.
This makes sense if you don't need to store any extra information on your
User object (e.g. firstName). But if you do, you may instead have your own
user class which you create and populate here by querying a database. This
would allow you to have custom data on the User object.

Finally, just make sure that supportsClass() returns true for User
objects with the same class as whatever user you return in loadUserByUsername().

If your authentication is stateless like in this example (i.e. you expect
the user to send the API key with every request and so you don't save the
login to the session), then you can simply throw the UnsupportedUserException
exception in refreshUser().

In order for your ApiKeyAuthenticator to correctly display a 401
http status when either bad credentials or authentication fails you will
need to implement the AuthenticationFailureHandlerInterface on your
Authenticator. This will provide a method onAuthenticationFailure which
you can use to create an error Response.

Now, activate it and your custom user provider (see How to Create a custom User Provider)
in the firewalls section of your security configuration
using the simple_preauth and provider keys respectively:

That's it! Now, your ApiKeyAuthenticator should be called at the beginning
of each request and your authentication process will take place.

The stateless configuration parameter prevents Symfony from trying to
store the authentication information in the session, which isn't necessary
since the client will send the apikey on each request. If you do need
to store authentication in the session, keep reading!

So far, this entry has described a situation where some sort of authentication
token is sent on every request. But in some situations (like an OAuth flow),
the token may be sent on only one request. In this case, you will want to
authenticate the user and store that authentication in the session so that
the user is automatically logged in for every subsequent request.

To make this work, first remove the stateless key from your firewall
configuration or set it to false:

Even though the token is being stored in the session, the credentials - in this
case the API key (i.e. $token->getCredentials()) - are not stored in the session
for security reasons. To take advantage of the session, update ApiKeyAuthenticator
to see if the stored token has a valid User object that can be used:

// src/AppBundle/Security/ApiKeyAuthenticator.php// ...classApiKeyAuthenticatorimplementsSimplePreAuthenticatorInterface{// ...publicfunctionauthenticateToken(TokenInterface$token,UserProviderInterface$userProvider,$providerKey){if(!$userProviderinstanceofApiKeyUserProvider){thrownew\InvalidArgumentException(sprintf('The user provider must be an instance of ApiKeyUserProvider (%s was given).',get_class($userProvider)));}$apiKey=$token->getCredentials();$username=$userProvider->getUsernameForApiKey($apiKey);// User is the Entity which represents your user$user=$token->getUser();if($userinstanceofUser){returnnewPreAuthenticatedToken($user,$apiKey,$providerKey,$user->getRoles());}if(!$username){// this message will be returned to the clientthrownewCustomUserMessageAuthenticationException(sprintf('API Key "%s" does not exist.',$apiKey));}$user=$userProvider->loadUserByUsername($username);returnnewPreAuthenticatedToken($user,$apiKey,$providerKey,$user->getRoles());}// ...}

Storing authentication information in the session works like this:

At the end of each request, Symfony serializes the token object (returned
from authenticateToken()), which also serializes the User object
(since it's set on a property on the token);

On the next request the token is deserialized and the deserialized User
object is passed to the refreshUser() function of the user provider.

The second step is the important one: Symfony calls refreshUser() and passes
you the user object that was serialized in the session. If your users are
stored in the database, then you may want to re-query for a fresh version
of the user to make sure it's not out-of-date. But regardless of your requirements,
refreshUser() should now return the User object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// src/AppBundle/Security/ApiKeyUserProvider.php// ...classApiKeyUserProviderimplementsUserProviderInterface{// ...publicfunctionrefreshUser(UserInterface$user){// $user is the User that you set in the token inside authenticateToken()// after it has been deserialized from the session// you might use $user to query the database for a fresh user// $id = $user->getId();// use $id to make a query// if you are *not* reading from a database and are just creating// a User object (like in this example), you can just return itreturn$user;}}

This entry has assumed that you want to look for the apikey authentication
on every request. But in some situations (like an OAuth flow), you only
really need to look for authentication information once the user has reached
a certain URL (e.g. the redirect URL in OAuth).

Fortunately, handling this situation is easy: just check to see what the
current URL is before creating the token in createToken():

// src/AppBundle/Security/ApiKeyAuthenticator.php// ...useSymfony\Component\Security\Http\HttpUtils;useSymfony\Component\HttpFoundation\Request;classApiKeyAuthenticatorimplementsSimplePreAuthenticatorInterface{protected$httpUtils;publicfunction__construct(HttpUtils$httpUtils){$this->httpUtils=$httpUtils;}publicfunctioncreateToken(Request$request,$providerKey){// set the only URL where we should look for auth information// and only return the token if we're at that URL$targetUrl='/login/check';if(!$this->httpUtils->checkRequestPath($request,$targetUrl)){return;}// ...}}

This uses the handy HttpUtils
class to check if the current URL matches the URL you're looking for. In this
case, the URL (/login/check) has been hardcoded in the class, but you
could also inject it as the second constructor argument.

Next, just update your service configuration to inject the security.http_utils
service: