Created
June 19, 2020 08:19
-
-
Save bytrangle/ea6440259e3f92f73dc6d67e7f06ea8f to your computer and use it in GitHub Desktop.
Generate base64 bearer token header in Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios') | |
// Testing on Twitter API. | |
// consumerKey and consumerSecret is a pair of keys associated with an app registered with Twitter API | |
const consumerKey = process.env.CONSUMER_KEY | |
const consumerSecret = process.env.CONSUMER_SECRET | |
const str = `${consumerKey}:${consumerSecret}` | |
// Base64 encode the request token and turn it into a value of the Authorization header | |
const authHeader = `Basic ${Buffer.from(str).toString('base64'}` | |
// Create an isntance of Axios | |
const instance = axios.create({ | |
baseURL: 'https://api.twitter.com' | |
}) | |
async function getBearToken (authHeader) { | |
instance.interceptors.request.use(config => { | |
config.headers = authHeader | |
// This param is required by the Twitter OAuth2 | |
config.params = { grant_type: 'client_credentials'} | |
return config | |
}) | |
try { | |
const response = await instance.post('/oauth2/token') | |
// Expect to see something like | |
// {token_type: 'bearer', access_token: 'XXXXXXXXXXXXXXXXXXXXXXX'} | |
console.log(response.data) | |
} | |
catch (error) { | |
console.log(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment