Sumair Baloch
Sumair Baloch

Reputation: 495

slack error "invalid_code" after sending request to oauth.access url

I am trying to authenticate my app with Slack. It was working perfectly fine for a few days, but now it's throwing me an error

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))

Response from server: { ok: false, error: 'invalid_code' }

The code I get is in this format. code=303414024726.805164905556.526d546072e9b2408e0743f42ca3bb5843553a6c3b930b1de2c1e31847b25448

I think this is JWT token but I am not sure.

Any help would be appreciated.

Upvotes: 7

Views: 5699

Answers (5)

Benjamin Carlsson
Benjamin Carlsson

Reputation: 610

According to Slack's API documentation, oauth.v2.access does not support JSON payloads, although most other endpoints do. You must send application/x-www-form-urlencoded.

Upvotes: 0

Dieferson Oliveira
Dieferson Oliveira

Reputation: 21

The solution was to send form-data instead of json in the request. As commented by Daniel Kent

Upvotes: 2

WillFry
WillFry

Reputation: 33

This seems like one of those error messages that is returned because of a wide range of reasons. None of the above worked for me, but when I generated a new client secret in "Settings" -> "Basic Information" -> "App Credentials" then it fixed the issue. This step revokes all existing tokens, which may have been part of what fixed the issue (although Li Xia's suggestion of revoking all tokens manually didn't work for me).

Upvotes: 1

Li Xia
Li Xia

Reputation: 29

Ran into the same issue where it worked then kept getting "invalid code" error in the response. Turns out, if there is already an OAuth token for the app/workspace, it will throw this error.

To fix this, go to "OAuth & Permissions" in the App management part of Slack, and revoke all your tokens (at the bottom of page.). On the next request, your request will return a new token.

Upvotes: 0

Haruna Akhmad
Haruna Akhmad

Reputation: 131

This is how i made it work

 let slackUrl = `https://slack.com/api/oauth.v2.access`;
let client_id = process.env.SLACK_CLIENT_ID;
let client_secret = process.env.SLACK_CLIENT_SECRET;
let details = {
    code,
    client_id,
    client_secret
}
var formBody = [];
for (var property in details) {
    var encodedKey = encodeURIComponent(property);
    var encodedValue = encodeURIComponent(details[property]);
    formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

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

let config = {
    method: 'POST',
    url: slackUrl,
    data: formBody,
    headers: _headers
};

let installation = await axios(config);

Upvotes: 1

Related Questions