How to sign-in a user based on custom HTTP headers in Drupal 8? 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 in Drupal with the login &quot;admin&quot;.
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 like so :
  public function applies(Request $request) {
    $name = $request-&gt;headers-&gt;get('X-USER-NAME');

    return isset($name);
  }

  /**
   * @inheritDoc
   */
  public function authenticate(Request $request) {
    $name = $request-&gt;headers-&gt;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 with an event subscriber :
class AdminRouteSubscriber extends \Drupal\Core\Routing\RouteSubscriberBase {

  /**
   * @inheritDoc
   */
  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection-&gt;all() as $route) {
      $path = $route-&gt;getPath();
      if (
        ($path == '/admin' || strpos($path, '/admin/') === 0)
      || ($path == '/node' || strpos($path, '/node/') === 0)
      || ($path == '/user' || strpos($path, '/user/') === 0)
      ) {
        $route-&gt;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 : &quot;The form has become outdated. Press the back button, copy any unsaved work in the form, and then reload the page.&quot;.
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.
I am a newbie in the Drupal world, am I on the good way or should I use a different approach ?
Thank you for your help :)
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.