Encountering a 401 error while attempting to exchange Faceit OAuth authorization code for access token

I am having issues with exchanging a code for a token on the Faceit OAuth. The documentation states the following:

Exchanging the Authorization Code for an Access Token
The third-party app needs to make a server-to-server call, providing the Authorization Code, Client ID, and Client Secret. In return, it will receive:
● an Access Token (used for calling the FACEIT API on behalf of the User)
● an ID Token (a digitally signed JWT containing user information from FACEIT)
● a Refresh Token (used to obtain a new Access Token when the current one expires).
To exchange the authorization code, your server must send an HTTPS POST request to the token endpoint obtained from the OpenID configuration endpoint under the key "token_endpoint."
The request should include HTTP Basic Authentication in the "Authorization" header (using your Client ID and Client Secret) and the "application/x-www-form-urlencoded" Content-type header. Include the following parameters in the POST body:
Field Description
code A one-time authorization code received on the callback page
grant_type This field must have the value "authorization_code," as per OAuth 2.0 specification

The code I have so far is as follows:

import axios from 'axios'
import qs from 'qs'

export async function authRoutes(app) {
  const clientId = process.env.CLIENT_ID
  const clientSecret = process.env.CLIENT_SECRET
  const credentials = `${clientId}:${clientSecret}`

  const base64Credentials = Buffer.from(credentials, 'utf-8').toString('base64')
  const tokenEndpoint = 'https://api.faceit.com/auth/v1/oauth/token'

  app.post('/register', async (request) => {
    const { code } = request.body
    const requestBody = qs.stringify({
      grant_type: 'authorization_code',
      code,
    })

    const headers = {
      Authorization: `Basic ${base64Credentials}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    }

    try {
      const tokenResponse = await axios.post(tokenEndpoint, requestBody, {
        headers,
      })
      return tokenResponse.data
    } catch (error) {
      console.log(error.message)
      return {
        error,
     }
   }
  })
}

When testing, I keep receiving a 401 BAD REQUEST error. Despite trying everything, I can't seem to get a response from this endpoint.

Although the endpoint is documented in the most recent Faceit documentation, I'm facing difficulties connecting to it.

Answer №1

To transform your credentials into a URL-encoded base64 string, you must make some modifications. The resulting base64 string should have the following changes:

  • Eliminate any instances of =
  • Substitute any occurrences of + with -
  • Replace any instances of / with _

You can achieve this with the following code snippet:

const urlEncodedString = base64String
    .replace(/=/g, '')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I effectively retrieve the JWT in a node environment?

I've successfully set up JWT authentication using Node.js. After the user signs in, Node.js generates a JWT and sends it back to be stored in the localStorage. However, I've encountered an issue when trying to access this token within the express ...

Having trouble with NextAuth's Google provider on Safari?

I've encountered an issue where the Google provider works perfectly on Chrome and other browsers, but fails to work on Safari. Despite going through the documentation thoroughly, I couldn't find any relevant information to resolve this. This is ...

Activating Button within Featherlight Modal

This is a follow up question from Featherlight hide div on Close After successfully resolving the issue with opening the lightbox, I have encountered another problem. I have added a submit button that should trigger an on('submit', function) whe ...

Sorting the keys of objects within an array

Currently, I am in the midst of an evaluation where I have the freedom to utilize any resources at my disposal. The task at hand involves using the .filter method to remove objects without a specific key. Here is the provided prompt... Create a function n ...

Iterate over the array elements in React by using Hooks on click

I am facing an issue with loading objects separately from a JSON file when a button is clicked. The problem occurs when the index goes out of bounds, resulting in a TypeError "Cannot read property 'content' of undefined" message. I have tried u ...

Execute jQuery after Angular has completed its loading process

I'm currently working on making some small adjustments to an existing website. This website was originally created using Angular. While my code is written with jQuery, I do have the flexibility to use any type of JavaScript necessary. Despite this, ...

Troubleshooting MySQL Database Insertion Errors caused by Dynamic Forms

<body> <?php $con = mysqli_connect('localhost','root','','cash'); $query = "SELECT DISTINCT category FROM cash"; $result = mysqli_query($con,$query); $dropDownList = &apo ...

Using HTML5 canvas to draw circles with additional metadata stored in variables

I'm designing a seating chart that will indicate spots with circles and show a tooltip on mouseover with the person's first name, last name, and possibly other details. I plan to use Kinetic.JS for region/tooltip support based on the tutorials I& ...

Using mousedown, mousemove, and mouseup to handle touch events in vanilla JavaScript instead of jQuery

Can someone guide me on how to set up a touch event handler in JavaScript using the mousedown, mousemove, and mouseup events? I would really appreciate any suggestions or tips! ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

Using jQuery to create tabs and display or hide tab-like content

I'm looking for a simpler way to achieve my goal without using the jQuery-UI library. Here is the setup, where I have navigation markup in the header: <ul> <li><a class="active" href="#" title="">Uno</a></li> <li& ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

Unveiling the approach to accessing a nested function with jQuery

While the title may be a bit misleading, I couldn't think of a better way to describe it. I've created a function that allows a small pop-up window to appear when a link is clicked (to confirm whether or not an article should be deleted). Addit ...

Reactstrap and React-router v4 are failing to redirect when there is a partial change in the address link

Within the header of my website, <NavItem> <NavLink tag={Link} to="/template/editor">Create New Template</NavLink> </NavItem> On the routing page of my website, <BrowserRouter> <div className="container-fluid"> ...

What should I do if one of my images fails to load after the previous one has loaded successfully?

My code is designed to create an animation using 3 canvases: one for the base image, one for the streamline wind map drawing, and another for an image covering part of the drawing. The following code displays the uploading of two images. var im ...

Adding x days to a Unix timestamp can be achieved by converting the Unix timestamp

Currently, I have the following code snippet: let currentTS = Math.floor(+new Date() / 1000) This code successfully retrieves the current date in a unix timestamp. However, my goal now is to append an additional 14 days to this unix timestamp. Could some ...

I need help figuring out the proper way to establish an indexing path in cosmos db using the nodejs sdk

I'm currently facing a challenge with setting up the indexing policy for one of my cosmosdb containers. Within my cosmosdb, I have a container that stores information about user sessions. Using the node sdk, I am defining the containers, partition key ...

The state initialization process is beginning with an [object Object] being passed into the setState function

Within the async function provided below, I am invoking stationData to verify that an array of objects is being passed into bartData (which currently consists of an empty array). Upon exploration, I have observed a response containing the anticipated array ...

Error: Unable to retrieve the value of a null property | ReactJS |

There are two textboxes and one button designed as material UI components. </p> <TextField id="chatidField" /> <br /> <p> <code>Enter Your Name:</code> <hr /> & ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...