X-CSRF-Token request header is missing - 403 forbidden error - REST API

Created on 1 July 2024, 2 months ago
Updated 20 August 2024, 19 days ago

Problem/Motivation

We have an App using simple_oath with Bearer tokens to authentication method. While using the custom login API using POST method, we started getting "X-CSRF-Token request header is missing" error. Even though, we have passed the bearer token in the header but we are getting the 403 forbidden error.

Steps to reproduce

1. Install "rest" & "simple_oauth" modules
2. Create consumers for client ID and secret - /admin/config/services/consumer
3. Create custom REST resource for user login.
4. Get the bearer token using the POST (/oauth/token)
5. REST API, pass the bearer token in Authorization header
6. Got the 403 forbidden error with message.
{
"message": "X-CSRF-Token request header is missing"
}

Proposed resolution

In the CSRF request header access file, we should add additional condition like to check the authentication method is other then Bearer.
Ex:
File: /core/lib/Drupal/Core/Access/CsrfRequestHeaderAccessCheck.php

// This check only applies if
    // 1. the user was successfully authenticated and
    // 2. the request comes with a session cookie.
    // 3. the authentication method is other then Bearer.
    if ($account->isAuthenticated()
      && $this->sessionConfiguration->hasSession($request)
      && strpos($request->headers->get('Authorization'), 'Bearer ') === FALSE
    ) {
      if (!$request->headers->has('X-CSRF-Token')) {
        return AccessResult::forbidden()->setReason('X-CSRF-Token request header is missing')->setCacheMaxAge(0);
      }
      $csrf_token = $request->headers->get('X-CSRF-Token');
      // @todo Remove validate call using 'rest' in 8.3.
      //   Kept here for sessions active during update.
      if (!$this->csrfToken->validate($csrf_token, self::TOKEN_KEY)
        && !$this->csrfToken->validate($csrf_token, 'rest')) {
        return AccessResult::forbidden()->setReason('X-CSRF-Token request header is invalid')->setCacheMaxAge(0);
      }
    }

Remaining tasks

No

User interface changes

No

API changes

No

Data model changes

No

Release notes snippet

No

🐛 Bug report
Status

RTBC

Version

11.0 🔥

Component
Base 

Last updated 24 minutes ago

Created by

🇮🇳India SenthilMohith Chennai

Live updates comments and jobs are added and updated live.
  • Novice

    It would make a good project for someone who is new to the Drupal contribution process. It's preferred over Newbie.

Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024