The error code "invalid_code" occurred when attempting to send a request to the oauth.access URL via Slack

Recently, I've been facing an issue while trying to authenticate my app with Slack. Everything was running smoothly for a few days until it started showing me an error message

invalid_code

const requestBody = qs.stringify({
    code: code,
    redirect_uri: redirect_uri,
    client_id: client_id,
    client_secret: client_secret
  });

  await axios
    .post(url, requestBody, config).
then(server => console.log(server)).catch(err => console.log(err))

The server responded with:

{ ok: false, error: 'invalid_code' }

The code I received looks something like this:

code=303414024726.805164905556.526d546072e9b2408e0743f42ca3bb5843553a6c3b930b1de2c1e31847b25448

I believe this code is in JWT token format, but I'm unsure. Any assistance on this matter would be highly appreciated.

Answer №1

It appears that this particular error message can be triggered by a variety of factors. Despite trying the solutions mentioned above without success, I was able to resolve the issue by creating a new client secret under "Settings" -> "Basic Information" -> "App Credentials". This action effectively invalidated all existing tokens, potentially playing a role in resolving the issue (even though attempting Li Xia's method of manually revoking all tokens did not yield results for me).

Answer №2

To resolve the issue, it was determined that sending form-data instead of JSON in the request was the best solution. This insight was provided by Daniel Kent.

Answer №3

This is the solution that worked for me

 const slackEndpoint = `https://slack.com/api/oauth.v2.access`;
const clientID = process.env.SLACK_CLIENT_ID;
const clientSecret = process.env.SLACK_CLIENT_SECRET;
const formData = {
    code,
    client_id: clientID,
    client_secret: clientSecret
}
var requestBody = [];
for (var prop in formData) {
    var encodedKey = encodeURIComponent(prop);
    var encodedVal = encodeURIComponent(formData[prop]);
    requestBody.push(encodedKey + "=" + encodedVal);
}
requestBody = requestBody.join("&");

const headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
};

let options = {
    method: 'POST',
    url: slackEndpoint,
    data: requestBody,
    headers: headers
};

let result = await axios(options);

Answer №4

Encountered a similar issue where the code was initially working but then started receiving an "invalid code" error in the response. As it turns out, this error occurs when there is an existing OAuth token for the app/workspace.

To resolve this issue, navigate to the "OAuth & Permissions" section in Slack's App management, and revoke all tokens (located at the bottom of the page). Upon your next request, a new token will be returned.

Answer №5

As per the information provided in Slack's API documentation, it is mentioned that while most other endpoints do support JSON payloads, the oauth.v2.access does not. In this case, you are required to send data in the format of

application/x-www-form-urlencoded
.

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

Converting JSON arrays to integers from strings in JavaScript: A step-by-step guide

When my application receives a Json string from the server (written in Java), I am faced with an issue when retrieving the data in JavaScript. The current format of the data looks like this: var data = [{"value":"3","label": "17 hr"}, {"value":"2", "labe ...

The output returned by the `reduce()` method cannot be displayed in HTML within a React component when using the `map()` function

Here is the output I am getting: https://i.sstatic.net/E4fK7.png It was generated by the code snippet below: var allblogs = [{ "banner": "41173047269_1594284317134_88820381534.png", "approved_status": 1, "posted_month": "July", "posted_ ...

Event listener added for a specific class, with certain individuals within the class not impacted

I've created a grid to serve as a menu, with a top row consisting of an unordered list (ul) containing three list items (li). Each of these li elements contains another ul with four li items inside. I've added an event listener that triggers when ...

Converting a nested JavaScript array into a PHP array

Having a javascript array is how my dilemma starts: foodList = ([apple,10,],[banana,20]) To convert this to a json object and send it to php, I perform the following action: var jsonData = JSON.stringify(foodList); The challenge now is extracting values ...

Developing numerous test suites within Selenium WebDriver

I am working on a testing script using selenium webdriver, phantomJS, and Mocha. My scripts are written in JavaScript. These are the variables declared outside the test modules: var afterLoginURL; var afterLoginTitle; var loginFlag = 0; I have two test ...

What is the functioning process of the angular method decorator?

The tutorial on creating custom decorators in Angular introduces a throttle decorator that utilizes the lodash throttle function. The implementation of this decorator can be seen below: import t from 'lodash.throttle'; export function throttle( ...

Executing an HTTP request with JavaScript to interact with Salesforce

Looking to connect Salesforce with Recosence, an external system. The scenario involves Recosense pushing data to Salesforce for storage. I have successfully created a post HTTP service and tested it in Postman, which generates an access token and records ...

What is the reason behind the improved performance I experience in Chrome with the Developer Console open?

Currently, I am developing a small canvas game completely from scratch using pure JavaScript. This game utilizes a 2D lighting algorithm that is akin to the one found here. It features only one light source and 25 polygons, resulting in approximately 30,0 ...

Reviewing user input for any inappropriate characters using jQuery's functionality

When a username is inputted into the input box, I want to make sure that only valid characters are accepted. The following code shows what I have so far; but what should I replace "SOMETHING" with in the regular expression? var numbers = new RegExp( ...

Updating the state of a component with Jest

I am currently working on updating the state of a component in jest. My goal is to ensure that when the state value of updated is changed to true, the new props do not alter the state value. After reading some answers, I believed that using the following ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

A guide to setting individual colors for each point in ThreeJS

Currently, I am experimenting with ThreeJS to generate a point cloud. My goal is to assign a distinct color to each individual point within the cloud based on its position. How can I go about setting specific colors for each vertex in the geometry and su ...

Comparing Products: Enhance Your Selection with Jquery to Add or Remove Items

I am looking to incorporate a "product compare feature" into the product list on my website. I am curious about how I can create a Query String URL from the product list page using jQuery, like the example below. The generated compare URL should follow th ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

svg stroke-dasharray malfunctioning

I've recently delved into the world of SVG's and I find myself scratching my head over the stroke-dasharray issue. I've scoured the web for answers to no avail, leaving me to believe that I'm overlooking something crucial. Despite imple ...

Ways to modify or add styles to p tags using the Document Object Model (DOM)

I am trying to change the font size variable in my P tag using the DOM, but I am struggling to find a way to access it and modify the styles. I attempted the following code: document.body.p.style.font-size = ""+p_var+"px"; I have also tried using various ...

Is it possible to use Node.js without resorting to template engines

Recently, I embarked on a journey to explore the world of backend development, focusing my attention on Node.js. As I delved into Express.js and familiarized myself with routing, a curious thought crossed my mind. Is there a method to transmit data direc ...

Building a Backbone Model by utilizing JSON information that was received

Is there a way to create a backbone model using data received from a web service, rather than manually inputting the information? Imagine you're getting JSON data from a webservice, and you'd like to directly use this JSON as a backbone model. H ...

The code stored in Github differs from the code deployed on the production server

I recently took over a project that had been outsourced to a web development company in the past, and it's built on the MEAN stack. After struggling to get the code from the Github repository to work properly, I decided to download the code directly ...