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: