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?