Notion access token returns 401 unauthorized

3.4k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

@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"
}'
0
On

had this 401 error because Postman settings were incorrect and not saved.

  1. Get postman collection: https://www.postman.com/notionhq/workspace/notion-s-api-workspace
  2. Setup collection with variables: enter image description here
  3. Make sure that the bearer token is set at the top level of the collection! enter image description here

After that, all the below API requests should work...