I would like to sign-in a user based on some custom headers in the HTTP request. Let's say I have an administrator account whose username is admin. If I send a request to Drupal with a custom header (X-USER-NAME: admin), I would like to be logged in with this user.

I tried to develop a custom authentication module to deal with this use-case.

public function applies(Request $request) {
  $name = $request->headers->get('X-USER-NAME');

  return isset($name);

public function authenticate(Request $request) {
  $name = $request->headers->get('X-USER-NAME');
  $user = user_load_by_name($name);

  return $user;

I then alter system routes so I can access them with my new authentication method.

class AdminRouteSubscriber extends \Drupal\Core\Routing\RouteSubscriberBase {

   * @inheritDoc
  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      $path = $route->getPath();
      if (
        ($path == '/admin' || strpos($path, '/admin/') === 0)
      || ($path == '/node' || strpos($path, '/node/') === 0)
      || ($path == '/user' || strpos($path, '/user/') === 0)
      ) {
        $route->setOption('_auth', ['headers_auth', 'cookie']);


I can now access a route to add a new content (let's say a new article), but when I submit the form to create this new content, I get the following error.

The form has become outdated. Press the back button, copy any unsaved work in the form, and then reload the page.

With my new authentication method, no cookie is set in the answer. I guess that there is some kind of CSRF token verification when submitting the form.

Am I on the good way or should I use a different approach?

1 Answer 1


That sounds like a very insecure way of allowing admin access to your site. Seems like a hacker just has to fake the header in the request to get access.

That said, you probably want to look at the various http authentication modules for Drupal 8 (E.g. google drupal 8 http authentication). Some quick starter links about this in core are:

https://www.drupal.org/docs/8/core/modules/basic_auth/overview https://www.drupal.org/docs/8/api/authentication-api/overview

As with most open source systems, the best way to figure out how to do something like this is to find code that does something similar and modify it to meet your needs.

  • Thanks for your answer ! I know it seems like an insecure way, but i will add some other custom access verification like range ip probably...
    – Erwan N
    Aug 25, 2020 at 5:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.