Image

Use Fetch and OAuth to Make Authenticated Requests for Drupal 8, 9, and 10

To perform POST, PUT, and DELETE operations to Drupal's JSON:API via a decoupled React application we need to use an OAuth access token. This requires first fetching the access token from Drupal, and then including it in the HTTP Authorization header of all future requests. We'll also need to handle the situation where our access token has expired, and we need to get a new one using refresh token.

To update our example application we need to first write some JavaScript code to manage the OAuth tokens. Then we'll update our existing React components to use that new code.

In this tutorial we'll:

  • Write code to exchange a username and password for an OAuth access token using the password grant flow
  • Create a wrapper for the JavaScript fetch() that handles inserting the appropriate HTTP Authorization headers
  • Update existing code that calls the Drupal JSON:API to use the new code

By the end of this tutorial you'll be able to use OAuth access tokens to make authenticated requests in a React application using fetch.