No authentication on fetchApiIndex

Created on 21 March 2023, almost 2 years ago
Updated 22 March 2023, almost 2 years ago

Problem/Motivation

I wanted to lock down the back end server by adding a permission on all jsonapi routes to restrict access to only an authenticated user based on the authentication credentials supplied by the front end. The problem with this is that the API Index route ('/jsonapi/') is also then restricted but the fetchApiIndex method does not add authorization headers when accessing it. You can alter the protection so that the API Index route was still accessible to anon users but this just returned an empty set since the anon user did not have access to any JSON API routes.

Steps to reproduce

Add simple 'jsonapi access' permission to all jsonapi routes. See last paragraph of https://www.drupal.org/docs/core-modules-and-themes/core-modules/jsonapi... . Front-end will give an error "Error: Failed to fetch API index".

Proposed resolution

Set authorisation header in fetchApiIndex if available in DrupalState.

Workaround

You can create a customFetcher that adds the authorisation header to any fetch to /jsoapi/.

    const customFetcher = async (url, requestInit) => {
    if (url === process.env.NEXT_PUBLIC_DRUPAL_BASE_URL + '/jsonapi/') {
      const tokenRequestBody = {
        grant_type: 'client_credentials',
        client_id: process.env.DRUPAL_CLIENT_ID,
        client_secret: process.env.DRUPAL_CLIENT_SECRET,
      };
      const token = await fetchToken(
        process.env.NEXT_PUBLIC_DRUPAL_BASE_URL + '/oauth/token',
        tokenRequestBody
      );
      const headers = new Headers();
      headers.append('Authorization', `${token['token_type']} ${token['access_token']}`);
      requestInit = {
        headers: headers,
      };
    }
    return fetch(url, requestInit);
  }
🐛 Bug report
Status

Active

Component

Code

Created by

🇬🇧United Kingdom dippers

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024