0

So i been trying to get access to the reddit api.

I registered to reddit. verified my mail. opened an app and got my credentials.

Followed this official documentation and also came across to this tutorial

All my efforts have failed and don't get any respond.

I am using nodejs. but also tried in postman and failed.

Tried 2 options using fetch and using axios:


    const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')



class RedditApi {

    clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
    clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";

    authenticationUrl = `https://www.reddit.com/api/v1/access_token`;

    BASE_URL = 'https://www.reddit.com/';

    tokenAuth = null;
    tokenExpirationTime = null;

    currencyObj = null;

    constructor(currencyObj) {
        this.currencyObj = currencyObj;
        console.log("constructor service")
    }

    async getAuthToken() {

        const bodyParams = new URLSearchParams({
            grant_type: "https://oauth.reddit.com/grants/installed_client",
            device_id: "DO_NOT_TRACK_THIS_DEVICE"
        });

        console.log(this.clientId2, 'this.clientId');
        debugger;

        const headersObj = {
            'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
            'Content-Type': 'application/x-www-form-urlencoded',
        };

        let response = null;
        try {
            response = await axios.post(this.authenticationUrl,
                bodyParams,
                {
                    headers: headersObj
                });
            debugger;
        } catch (error) {
            debugger;
            console.error(error);
            console.log(error.stack);
            return null;
        }
    }


    async getAuthToken2() {
        try {
            // Creating Body for the POST request which are URL encoded
            const params = new URLSearchParams()
            params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
            params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')

            // Trigger POST to get the access token
            const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
                }
            }).then(res => {
                debugger;

                return res.text()
            })
            debugger;

            if (!tokenData.error) {
                debugger;

                res.send(trendingResult)
            }
            res.status(tokenData.error).send(tokenData.message)
        } catch (error) {
            debugger;
            console.log(error)
        }
    }
}

module.exports = RedditApi;

when using axios i get this respond: "Request failed with status code 401"

When using fetch i get this respond: "'

403 Forbidden

\nRequest forbidden by administrative rules.\n\n'"

Anybody knows what is the problem and how can i fix it? Many thanks!

codingnighter2000
  • 497
  • 1
  • 7
  • 24
  • 1
    _"You must supply your OAuth2 client's credentials via HTTP Basic Auth for this request. The "user" is the client_id, the "password" is the client_secret."_ - I don't see you supplying the password portion in `Basic ${Buffer.from(\`${this.clientId2}:\`).toString('base64')}` – CBroe Mar 24 '22 at 10:56
  • 1
    (And why are you using this convoluted way to provide the credentials in the first place, axios takes an `auth` option for that, https://axios-http.com/docs/req_config) – CBroe Mar 24 '22 at 10:58
  • @CBroe that did the trick! thank you! i was following this tutorial https://ranjithnair.github.io/2018/02/27/Reddit-Application-Oauth.html and some other in youtube and they said yo leave the password empty. also looked at the official docs. i guess thing have changes – codingnighter2000 Mar 24 '22 at 11:10
  • @CBroe reddit api want you first to get the auth token and only then make the request. not sure if what u r suggesting is possible in this case. – codingnighter2000 Mar 24 '22 at 11:11
  • I am just talking about a different way to provide the HTTP Basic Auth credentials, you don't have to assemble them in `username:password` format, apply base64 encoding and then stuff the whole thing into a header yourself - you can simply provide an object `auth: { username: '...', password: '...' }` in the request options, and axios will handle the rest for you. – CBroe Mar 24 '22 at 11:14
  • I get what u said now. tried it and it work. once again thank you! – codingnighter2000 Mar 24 '22 at 11:24

0 Answers0