0

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 "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 like so :

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

    return isset($name);
  }

  /**
   * @inheritDoc
   */
  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 with an event subscriber :

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.

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 :)

0

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.

1
  • 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 '20 at 5:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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