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!