Skip to content

updated How to Authenticate Users with API Keys #6157

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 50 additions & 9 deletions cookbook/security/api_key_authentication.rst
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ value and then a User object is created::
// $apiKey = $request->headers->get('apikey');

if (!$apiKey) {
throw new BadCredentialsException('No API key found');
throw new BadCredentialsException();

// or to just skip api key authentication
// return null;
Expand All @@ -66,6 +66,11 @@ value and then a User object is created::
);
}

public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
}

public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
if (!$userProvider instanceof ApiKeyUserProvider) {
Expand Down Expand Up @@ -97,11 +102,6 @@ value and then a User object is created::
$user->getRoles()
);
}

public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
}
}

.. versionadded:: 2.8
Expand Down Expand Up @@ -196,7 +196,7 @@ The ``$userProvider`` might look something like this::
null,
// the roles for the user - you may choose to determine
// these dynamically somehow based on the user
array('ROLE_USER')
array('ROLE_API')
);
}

Expand Down Expand Up @@ -268,6 +268,7 @@ 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``
Expand All @@ -281,7 +282,7 @@ exception in ``refreshUser()``.
Handling Authentication Failure
-------------------------------

In order for your ``ApiKeyAuthenticator`` to correctly display a 403
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 :class:`Symfony\\Component\\Security\\Http\\Authentication\\AuthenticationFailureHandlerInterface` on your
Authenticator. This will provide a method ``onAuthenticationFailure`` which
Expand All @@ -308,7 +309,7 @@ you can use to create an error ``Response``.
// this contains information about *why* authentication failed
// use it, or return your own message
strtr($exception->getMessageKey(), $exception->getMessageData())
, 403)
, 401)
}
}

Expand Down Expand Up @@ -434,6 +435,46 @@ using the ``simple_preauth`` and ``provider`` keys respectively:
),
));

If you have defined `access_control`, make sure to add new entry:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be enclosed by double instead of single backticks.


.. configuration-block::

.. code-block:: yaml

# app/config/security.yml
security:
# ...

access_control:
- { path: ^/admin, roles: ROLE_API }

.. code-block:: xml

<!-- app/config/security.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:srv="http://symfony.com/schema/dic/services"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">

<rule path="^/admin"
role="ROLE_API"
/>
</srv:container>

.. code-block:: php

// app/config/security.php
$container->loadFromExtension('security', array(
'access_control' => array(
array(
'path' => '^/admin',
'role' => 'ROLE_API',
),
),
));

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

Expand Down