1

I am trying to convert a Python app I made some years ago to a (better) NodeJS implementation. The function in question obtains an access token from the Twitter api to attach to future requests, but my implementation returns 403 bad request. Here is a the functional Python implementation..

def get_bearer_header():
    uri_token_endpoint = 'https://api.twitter.com/oauth2/token'
    key_secret = f"{twitter_creds.CONSUMER_KEY}:{twitter_creds.CONSUMER_KEY_SECRET}".encode('ascii')
    b64_encoded_key = base64.b64encode(key_secret)
    b64_encoded_key = b64_encoded_key.decode('ascii')

    auth_headers = {
        'Authorization': 'Basic {}'.format(b64_encoded_key),
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }

    auth_data = {
        'grant_type': 'client_credentials'
        }

    auth_resp = requests.post(uri_token_endpoint, headers=auth_headers, data=auth_data)
    bearer_token = auth_resp.json()['access_token']

    bearer_header = {
        'Accept-Encoding': 'gzip',
        'Authorization': 'Bearer {}'.format(bearer_token),
        'oauth_consumer_key': twitter_creds.CONSUMER_KEY 
    }
    return bearer_header

and here is the JS implementation so far..

export const getBearerHeader = async () => {
    const keyAndSecret = btoa(`${config.twitterApi.consumerKey}:${config.twitterApi.consumerKeySecret}`)
    const buff = Buffer.from(keyAndSecret, 'utf-8');
    const b64KeyAndSecret = buff.toString('base64');
    const body = new URLSearchParams({
        'grant_type': 'client_credentials'
    })
    const url = config.twitterApi.oauthTokenEndpoint
    const headers =  {
        'Authorization': `Basic ${b64KeyAndSecret}`,
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }

    const resp = await axios.post(url, body, headers)
    console.log("RESPONSE.data")
    console.log(resp.data)
}

the request looks fine according to twitter docs, but my response says 403!

Any assistance appreciated!

HubertBlu
  • 747
  • 1
  • 7
  • 20

1 Answers1

1

Get Twitter access token v2 by python and node.js code.

To create API Key and Secret from Twitter Developer Portal

Main idea to use curl commend for getting access token. POST oauth2/token

Using config.json file

{
    "API_KEY" : "Xx7MxxxxxTkzxxxxxq9xxxxxQ",
    "API_KEY_SECRET" : "om4QxxxxxPrcPlxxxxxFikDxxxxxoC5mQxxxxxLy7M17xxxxxK"
}

Node.js code

const axios = require('axios')
const config = require('./config.json');

const getAccessToken = async () => {
    try {
        const resp = await axios.post(
            'https://api.twitter.com/oauth2/token',
            '',
            {
                params: {
                    'grant_type': 'client_credentials'
                },
                auth: {
                    username: config.API_KEY,
                    password: config.API_KEY_SECRET
                }
            }
        );
        console.log(resp.data);
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
};

getAccessToken();

python code

import requests
import json
import ast

def get_access_token():
    with open('config.json') as config_file:
        data = json.load(config_file)

        params = {
            'grant_type': 'client_credentials',
        }

        response = requests.post('https://api.twitter.com/oauth2/token', params=params, auth=(data['API_KEY'], data['API_KEY_SECRET']))

        print(response.content)
        json_data = ast.literal_eval(response.content.decode("UTF-8"))
        return json_data['access_token']


print(get_access_token())

run from terminal enter image description here

Bench Vue
  • 5,257
  • 2
  • 10
  • 14
  • the documentation was telling me to encode to b64 and what not which i did originally and it worked. amazed that this (simpler) solution works, thanks! – HubertBlu Aug 30 '22 at 09:29
  • any idea why my node version does work? have they updated the api the last few weeks? or does axios automatically b64 encode the body? I am confused as to how the implementations could be so different but still work – HubertBlu Aug 30 '22 at 09:58
  • I did not know, twitter API history. I just implemented both language from Twitter web site [POST oauth2/token](https://developer.twitter.com/en/docs/authentication/api-reference/token). I use [curl to other language online service](https://curlconverter.com/) – Bench Vue Aug 30 '22 at 10:27