Create a custom authentication provider
Last updated on
27 July 2025
Use case
Instead of using basic auth, create an authentication provider that authenticates the requests with the X-Auth-Token header.
Code changes
1. Service
services:
mymodule.authentication.auth_token:
class: Drupal\mymodule\Authentication\AuthToken
tags:
- { name: authentication_provider, provider_id: 'token_auth', priority: 10 }
2. AuthToken class
<?php
namespace Drupal\mymodule\Authentication;
use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Drupal\Core\Session\UserSession;
use Symfony\Component\HttpFoundation\Request;
/**
* Authentication provider to validate requests with token in header.
*/
class AuthToken implements AuthenticationProviderInterface {
/**
* {@inheritdoc}
*/
public function applies(Request $request) {
return $request->headers->has('X-Auth-Token');
}
/**
* {@inheritdoc}
*/
public function authenticate(Request $request) {
$token = $request->headers->get('X-Auth-Token');
// Validate the token.
// Return NULL, if validation failed.
// return NULL;
// Return a session if the request passes the validation.
return new UserSession();
}
}
3. Add auth to route(s)
mymodule.secured_page:
path: '/mymodule/secured-page'
defaults:
_controller: 'Drupal\mymodule\Controller\PageController::getPage'
requirements:
_permission: 'access content'
options:
_auth: [ 'token_auth' ]
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.