Access tokens or API tokens are commonly used as authentication mechanismin API contexts. The access token is a string, obtained during authentication(using the application or an authorization server). The access token's roleis to verify the user identity and receive consent before the token isissued.
Access tokens can be of any kind, for instance opaque strings,JSON Web Tokens (JWT) or SAML2 (XML structures). Please refer to theRFC6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage fora detailed specification.
Using the Access Token Authenticator
This guide assumes you have setup security and have created a user objectin your application. Follow the main security guide ifthis is not yet the case.
1) Configure the Access Token Authenticator
To use the access token authenticator, you must configure a token_handler
.The token handler receives the token from the request and returns thecorrect user identifier. To get the user identifier, implementations mayneed to load and validate the token (e.g. revocation, expiration time,digital signature, etc.).
123456
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: App\Security\AccessTokenHandler
This handler must implementAccessTokenHandlerInterface:
1234567891011121314151617181920212223242526272829
// src/Security/AccessTokenHandler.phpnamespace App\Security;use App\Repository\AccessTokenRepository;use Symfony\Component\Security\Core\Exception\BadCredentialsException;use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;class AccessTokenHandler implements AccessTokenHandlerInterface{ public function __construct( private AccessTokenRepository $repository ) { } public function getUserBadgeFrom(string $accessToken): UserBadge { // e.g. query the "access token" database to search for this token $accessToken = $this->repository->findOneByValue($accessToken); if (null === $accessToken || !$accessToken->isValid()) { throw new BadCredentialsException('Invalid credentials.'); } // and return a UserBadge object containing the user identifier from the found token // (this is the same identifier used in Security configuration; it can be an email, // a UUID, a username, a database ID, etc.) return new UserBadge($accessToken->getUserId()); }}
The access token authenticator will use the returned user identifier toload the user using the user provider.
Caution
It is important to check the token if is valid. For instance, theexample above verifies whether the token has not expired. Withself-contained access tokens such as JWT, the handler is required toverify the digital signature and understand all claims, especiallysub
, iat
, nbf
and exp
.
2) Configure the Token Extractor (Optional)
The application is now ready to handle incoming tokens. A token extractorretrieves the token from the request (e.g. a header or request body).
By default, the access token is read from the request header parameterAuthorization
with the scheme Bearer
(e.g. Authorization: Bearerthe-token-value
).
Symfony provides other extractors as per the RFC6750:
header
(default)- The token is sent through the request header. Usually
Authorization
with theBearer
scheme. query_string
- The token is part of the request query string. Usually
access_token
. request_body
- The token is part of the request body during a POST request. Usually
access_token
.
Caution
Because of the security weaknesses associated with the URI method,including the high likelihood that the URL or the request bodycontaining the access token will be logged, methods query_string
and request_body
SHOULD NOT be used unless it is impossible totransport the access token in the request header field.
You can also create a custom extractor. The class must implementAccessTokenExtractorInterface.
123456789101112
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: App\Security\AccessTokenHandler # use a different built-in extractor token_extractors: request_body # or provide the service ID of a custom extractor token_extractors: 'App\Security\CustomTokenExtractor'
It is possible to set multiple extractors. In this case, the order isimportant: the first in the list is called first.
123456789
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: App\Security\AccessTokenHandler token_extractors: - 'header' - 'App\Security\CustomTokenExtractor'
3) Submit a Request
That's it! Your application can now authenticate incoming requests using anAPI token.
Using the default header extractor, you can test the feature by submittinga request like this:
12
$ curl -H 'Authorization: Bearer an-accepted-token-value' \ https://localhost:8000/api/some-route
Customizing the Success Handler
By default, the request continues (e.g. the controller for the route isrun). If you want to customize success handling, create your own successhandler by creating a class that implementsAuthenticationSuccessHandlerInterfaceand configure the service ID as the success_handler
:
1234567
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: App\Security\AccessTokenHandler success_handler: App\Security\Authentication\AuthenticationSuccessHandler
Tip
If you want to customize the default failure handling, use thefailure_handler
option and create a class that implementsAuthenticationFailureHandlerInterface.
Using OpenID Connect (OIDC)
OpenID Connect (OIDC) is the third generation of OpenID technology and it's aRESTful HTTP API that uses JSON as its data format. OpenID Connect is anauthentication layer on top of the OAuth 2.0 authorization framework. It allowsto verify the identity of an end user based on the authentication performed byan authorization server.
1) Configure the OidcUserInfoTokenHandler
The OidcUserInfoTokenHandler
requires the symfony/http-client
package tomake the needed HTTP requests. If you haven't installed it yet, run this command:
1
$ composer require symfony/http-client
Symfony provides a generic OidcUserInfoTokenHandler
to call your OIDC serverand retrieve the user info:
1234567
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: oidc_user_info: https://www.example.com/realms/demo/protocol/openid-connect/userinfo
Following the OpenID Connect Specification, the sub
claim is used as useridentifier by default. To use another claim, specify it on the configuration:
123456789
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: oidc_user_info: claim: email base_uri: https://www.example.com/realms/demo/protocol/openid-connect/userinfo
The oidc_user_info
token handler automatically creates an HTTP client withthe specified base_uri
. If you prefer using your own client, you canspecify the service name via the client
option:
12345678
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: oidc_user_info: client: oidc.client
By default, the OidcUserInfoTokenHandler
creates an OidcUser
with theclaims. To create your own user object from the claims, you mustcreate your own UserProvider:
12345678910
// src/Security/Core/User/OidcUserProvider.phpuse Symfony\Component\Security\Core\User\AttributesBasedUserProviderInterface;class OidcUserProvider implements AttributesBasedUserProviderInterface{ public function loadUserByIdentifier(string $identifier, array $attributes = []): UserInterface { // implement your own logic to load and return the user object }}
2) Configure the OidcTokenHandler
The OidcTokenHandler
requires the web-token/jwt-library
package.If you haven't installed it yet, run this command:
1
$ composer require web-token/jwt-library
Symfony provides a generic OidcTokenHandler
to decode your token, validateit and retrieve the user info from it:
123456789101112131415
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: oidc: # Algorithms used to sign the JWS algorithms: ['ES256', 'RS256'] # A JSON-encoded JWK keyset: '{"keys":[{"kty":"...","k":"..."}]}' # Audience (`aud` claim): required for validation purpose audience: 'api-example' # Issuers (`iss` claim): required for validation purpose issuers: ['https://oidc.example.com']
7.1
The support of multiple algorithms to sign the JWS was introduced in Symfony 7.1.In previous versions, only the ES256
algorithm was supported.
Following the OpenID Connect Specification, the sub
claim is used bydefault as user identifier. To use another claim, specify it on theconfiguration:
123456789101112
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: oidc: claim: email algorithms: ['ES256', 'RS256'] keyset: '{"keys":[{"kty":"...","k":"..."}]}' audience: 'api-example' issuers: ['https://oidc.example.com']
By default, the OidcTokenHandler
creates an OidcUser
with the claims. Tocreate your own User from the claims, you mustcreate your own UserProvider:
12345678910
// src/Security/Core/User/OidcUserProvider.phpuse Symfony\Component\Security\Core\User\AttributesBasedUserProviderInterface;class OidcUserProvider implements AttributesBasedUserProviderInterface{ public function loadUserByIdentifier(string $identifier, array $attributes = []): UserInterface { // implement your own logic to load and return the user object }}
Using CAS 2.0
7.1
The support for CAS token handlers was introduced in Symfony 7.1.
Central Authentication Service (CAS) is an enterprise multilingual singlesign-on solution and identity provider for the web and attempts to be acomprehensive platform for your authentication and authorization needs.
Configure the Cas2Handler
Symfony provides a generic Cas2Handler
to call your CAS server. It requiresthe symfony/http-client
package to make the needed HTTP requests. If youhaven't installed it yet, run this command:
1
$ composer require symfony/http-client
You can configure a cas
token handler as follows:
12345678
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: cas: validation_url: https://www.example.com/cas/validate
The cas
token handler automatically creates an HTTP client to callthe specified validation_url
. If you prefer using your own client, you canspecify the service name via the http_client
option:
123456789
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: cas: validation_url: https://www.example.com/cas/validate http_client: cas.client
- By default the token handler will read the validation URL XML response with
-
cas
prefix but you can configure another prefix:
123456789
# config/packages/security.yamlsecurity: firewalls: main: access_token: token_handler: cas: validation_url: https://www.example.com/cas/validate prefix: cas-example
Creating Users from Token
Some types of tokens (for instance OIDC) contain all information requiredto create a user entity (e.g. username and roles). In this case, you don'tneed a user provider to create a user from the database:
12345678910111213141516171819
// src/Security/AccessTokenHandler.phpnamespace App\Security;// ...class AccessTokenHandler implements AccessTokenHandlerInterface{ // ... public function getUserBadgeFrom(string $accessToken): UserBadge { // get the data from the token $payload = ...; return new UserBadge( $payload->getUserId(), fn (string $userIdentifier) => new User($userIdentifier, $payload->getRoles()) ); }}
When using this strategy, you can omit the user_provider
configurationfor stateless firewalls.