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:
- Front-end redirects client to authorization page.
- Once authorized I handle the redirection to "http://localhost:8081/oauth_callback" to get the temporary code.
- This code is sent to back-end where I try to retrieve the access token.
- We run into problems
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 axios.post('https://www.reddit.com/api/v1/access_token', 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: 'https://www.reddit.com/api/v1/access_token',
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: https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token
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.
Thanks
Edit: I resolved the problem. The redirection added "#_" at the end of the url and therefore at the end of the code...