
Security News
High Salaries No Longer Enough to Attract Top Cybersecurity Talent
A survey of 500 cybersecurity pros reveals high pay isn't enough—lack of growth and flexibility is driving attrition and risking organizational security.
@twitter-api-v2/plugin-token-refresher
Advanced tools
User-context OAuth2 access token auto-refresher for twitter-api-v2
Automatic OAuth2 user-context access token refresher plugin for twitter-api-v2
Twitter API v2 introduce a new way to handle user-context with OAuth2. It gives access to simple tokens, named Bearer tokens, having a dedicated lifetime (usually 2 hours).
If your Twitter app uses user-context more than this time-range, you'll need to handle token refreshes.
A token refresh is a dedicated call to have a fresh, new couple of access+refresh tokens.
To smoothen usage of API v2, this plugin allows you to completely overpass this limitation and handles the refresh for you! When a 401 or a 403 error is received from Twitter, it will refresh token automatically and restart the pending request.
import { TwitterApi } from 'twitter-api-v2'
import { TwitterApiAutoTokenRefresher } from '@twitter-api-v2/plugin-token-refresher'
const credentials = { clientId: '<oauth2 client ID>', clientSecret: '<oauth2 client secret>' }
// Obtained first through OAuth2 auth flow
const tokenStore = { accessToken: '', refreshToken: '' }
const autoRefresherPlugin = new TwitterApiAutoTokenRefresher({
refreshToken: tokenStore.refreshToken,
refreshCredentials: credentials,
onTokenUpdate(token) {
tokenStore.accessToken = token.accessToken
tokenStore.refreshToken = token.refreshToken!
// store in DB/Redis/...
},
onTokenRefreshError(error) {
console.error('Refresh error', error)
},
})
const client = new TwitterApi(tokenStore.accessToken, { plugins: [autoRefresherPlugin] })
// use {client}, if needed, token will be refreshed with {refreshToken}
Requirements
clientId
and clientSecret
express
one, but we need one to "welcome back" the user after its redirection to Twitter
express
callbackUrl
setLoginVerifierForState(state, verifier)
getLoginVerifierFromState(state): verifier
setLoginCredentials(twitterUserId, credentials)
getLoginCredentials(twitterUserId): credentials
First, obtain access to user credentials by redirecting the user to Twitter portal, in order to "accept" your app to be linked to their profile.
import { TwitterApi } from 'twitter-api-v2'
const loginClient = new TwitterApi({ clientId, clientSecret })
// Don't forget to specify 'offline.access' in scope list, you want to refresh your token later
const { url, codeVerifier, state } = loginClient.generateOAuth2AuthLink(callbackUrl, { scope: ['tweet.read', 'users.read', 'offline.access', ...] });
// Store {state} and {codeVerifier}
setLoginVerifierForState(state, codeVerifier)
// Redirect user to {url}
Once user has clicked on url
, approved your app, they will be redirected to callbackUrl
.
This should match a route on your web server.
We will suppose you use /callback
here, adjust with your configuration.
import { TwitterApi } from 'twitter-api-v2'
// We still need a client with same credentials as in step 1
const loginClient = new TwitterApi({ clientId, clientSecret })
app.get('/callback', async (req, res) => {
// Extract state and code from query string
const { state, code } = req.query;
// Check if a verifier is associated with given state
const codeVerifier = getLoginVerifierFromState(state)
if (!codeVerifier || !code) {
return res.status(400).send('You denied the app or your session expired!')
}
try {
// Get tokens
const { client, accessToken, refreshToken } = await client.loginWithOAuth2({ code, codeVerifier, redirectUri: callbackUrl })
// Get user ID
const concernedUser = await client.v2.me()
// Store credentials
setLoginCredentials(concernedUser.data.id, { accessToken, refreshToken })
} catch (e) {
return res.status(403).send('Invalid verifier or access tokens!')
}
})
You now have credentials for user {id}
. We will now use them.
import { TwitterApi } from 'twitter-api-v2'
import { TwitterApiAutoTokenRefresher } from '@twitter-api-v2/plugin-token-refresher'
const { accessToken, refreshToken } = getLoginCredentials(id)
const autoRefresherPlugin = new TwitterApiAutoTokenRefresher({
refreshToken,
refreshCredentials: { clientId, clientSecret },
onTokenUpdate(token) {
setLoginCredentials(id, token)
},
})
const client = new TwitterApi(accessToken, { plugins: [autoRefresherPlugin] })
// - Now, make requests -
// If token is expired, it will automatically by renewed.
await client.v2.me()
If you want to change settings or apply plugins to client that is used to refresh token with your clientId
and clientSecret
,
give an instance of TwitterApi
instead of your credentials:
const autoRefresherPlugin = new TwitterApiAutoTokenRefresher({
refreshCredentials: new TwitterApi({ clientId, clientSecret }, { plugins: [rateLimitPlugin] }),
...
})
FAQs
User-context OAuth2 access token auto-refresher for twitter-api-v2
The npm package @twitter-api-v2/plugin-token-refresher receives a total of 834 weekly downloads. As such, @twitter-api-v2/plugin-token-refresher popularity was classified as not popular.
We found that @twitter-api-v2/plugin-token-refresher demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A survey of 500 cybersecurity pros reveals high pay isn't enough—lack of growth and flexibility is driving attrition and risking organizational security.
Product
Socket, the leader in open source security, is now available on Google Cloud Marketplace for simplified procurement and enhanced protection against supply chain attacks.
Security News
Corepack will be phased out from future Node.js releases following a TSC vote.