'Notion access token returns 401 unauthorized

After I got the temporary code, I send it to exchange access token, but it returns 401 unauthorized error. Here is my code:

const resp = await fetch("https://api.notion.com/v1/oauth/token", { method:'POST', 
    client_id: notionClientId, client_secret: notionClientSecret,
        headers: { "Content-Type": "application/json" },
        data: { code, grant_type: "authorization_code"} })

What's wrong here?. There is no much information in Notion documentation.

Edit: i am using localhost as my redirect URL in the integration setup.



Solution 1:[1]

@Nithur:

I went through this process a while ago. I'd recommend running this process via Postman. There you can setup everything easily, refer Notion's Authorization documentation. After reviewing your snippet, I believe you are not forming your POST request properly.

If you still want to set this on your project, here's a snippet that may help you using JavaScript Fetch:

var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic NDYzNTU4YTMtNzI1ZS00ZjM3LWI2ZDMtMDg4OTg5NGY2OGRlOnNlY3JldF95b3VfZm91bmRfbXlfZmFrZV9zZWNyZXQ=");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "grant_type": "authorization_code",
  "code": "e202e8c9-0990-40af-855f-ff8f872b1ec6",
  "redirect_uri": "https://example.com/auth/notion/callback"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://api.notion.com/v1/oauth/token", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

If you want to try it out from Postman replacing the values with your own, import this cURL snippet as raw text:

curl --location --request POST 'https://api.notion.com/v1/oauth/token' \
--header 'Authorization: Basic NDYzNTU4YTMtNzI1ZS00ZjM3LWI2ZDMtMDg4OTg5NGY2OGRlOnNlY3JldF95b3VfZm91bmRfbXlfZmFrZV9zZWNyZXQ=' \
--header 'Content-Type: application/json' \
--data-raw '{
    "grant_type": "authorization_code",
    "code": "e202e8c9-0990-40af-855f-ff8f872b1ec6",
    "redirect_uri": "https://example.com/auth/notion/callback"
}'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DharmanBot