Summary
This short post demonstrates the steps necessary to fetch an app-only bearer token via Twitter's OAuth2 interface using Node.js. That token would then be subsequently used to access Twitter's APIs. This post follows the steps explained on the Twitter developer site here.
Set-up
- Create a developer account as described here.
- Create an 'application' as described here.
- At this point, you have a 'Consumer Key' and 'Consumer Secret'. Those two strings will be used in the code shown below.
Code
Create the Consumer Token
Per the Twitter documentation, the Consumer Key and Secret need to be URL encoded, concatentated, and then base64-encoded.const CONSUMER_KEY = process.env.CONSUMER_KEY; const CONSUMER_SECRET = process.env.CONSUMER_SECRET; function urlEncode (str) { return encodeURIComponent(str) .replace(/!/g, '%21') .replace(/'/g, '%27') .replace(/\(/g, '%28') .replace(/\)/g, '%29') .replace(/\*/g, '%2A') } const consumerToken = btoa(urlEncode(CONSUMER_KEY) + ':' + urlEncode(CONSUMER_SECRET));
Fetch the Bearer Token
Code below uses node-fetch to execute a HTTP POST to the Twitter OAuth2 interface. If the fetch is successful, the bearer token is inside a JSON object returned by that interface.return fetch(url, { method: 'POST', headers: { 'Authorization' : 'Basic ' + consumerToken, 'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8' }, body : 'grant_type=client_credentials' }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Response Status: ' + response.status); } }) .then(json => { if (json.token_type == 'bearer') { return json.access_token; } else { throw new Error('Invalid token type: ' + json.token_type); } });
Source
Full source here: https://github.com/joeywhelan/authTest
Copyright ©1993-2024 Joey E Whelan, All rights reserved.