Can’t get Reddit Oauth acces token, I keep getting invalid_grant error

I am trying to build a web app to summarize useful informations and one of the things I want to add is a Reddit widget.

I spent the entire day struggling with Axios because for some reason my request doesn’t work. I would just like to say that I have already built an App using Reddit api in Kotlin and it works fine so I understand how the api and OAuth works, the problem is (I think) my understanding of Axios.

Due to the fact that I keep getting { error: ‘invalid_grant’ } I think that the problem comes from Axios encoding my request body and therefore modifying the code I use to retrieve the access_token.

I have a front-end (Vue.js) and a back-end (Node, Express). To make requests I use Axios.

So here is the code logic:

This is the function that I use to get the access token:

async function getToken(uniqueCode) {
    let authString = `${client_id}:${client_secret}`;
    authString = Buffer.from(authString).toString('base64');

    let requestHeaders = {
        'Authorization': `Basic ${authString}`,
        'Content-Type': 'application/x-www-form-urlencoded'

    const params = new URLSearchParams();
    params.append("grant_type", "authorization_code");
    params.append("code", uniqueCode);
    params.append("redirect_uri", "http://localhost:8081/oauth_callback");

    let res = await'', params, {headers: requestHeaders});

    return res.body.access_token

I tried the same request, with same headers and parameters, using postman and it works fine.

console.log(res) dumps a lot of informations including :

headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: 'Basic {removed by me}',
      'User-Agent': 'axios/0.24.0',
      'Content-Length': 129
method: 'post',
url: '',
data: 'grant_type=authorization_code&code=LiTC051x3nEKqXSbU0spuHgKHHaLGw%23_&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Foauth_callback'

Obviously I used this code to revoke it before posting.

The parameters seems consistent with the documentation I followed:

For me the messy part here is that code’s special characters are encoded but I’m not sure because the format is application/x-www-form-urlencoded so maybe it is normal, maybe not, I don’t know.

If someone could help me getting my code working it would be very nice.


Source: JavaSript – Stack Overflow

November 14, 2021
Category : News
Tags: axios | javascript | oauth-2.0 | reddit-access-token

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.