'I am trying to implement OAuth for twitter API and am confused about sessions and all the different keys
I am trying to implement OAuth 1.0a 3 legged auth-flow for a Twitter bot using Javascript and the npm packages twitter-api-v2, but I am finding it difficult to understand the flow. What is oauth_verifier, oauth_token and oauth_token_secret?
When I log the auth link, it also shows me the oauth_token and oauth_token_secret. why can't I just I save these values?
Here's how I believe oauth works right now:
- I generate a link,
- I click on the link,
- I authorize my app, and twitter takes me to my callback URL where I can save the
oauth_verifier, and request twitter for theoauth_tokenandoauth_token_secretfor that account. - now I can create a client using those tokens and secrets, and make requests and tweet on behalf of a user.
Here's where stuff gets blurry. why is oauth_token in the req.query, but oauth_token_secret in req.session? and if we can extract oauth_token from req.query, why do we need to make another request using the oauth_verifier?
here's my code:
app.get("/callback", (req, res) => {
// Extract tokens from query string
const { oauth_token, oauth_verifier } = req.query;
// Get the saved oauth_token_secret from session
const { oauth_token_secret } = req.session;
if (!oauth_token || !oauth_verifier || !oauth_token_secret) {
return res.status(400).send("You denied the app or your session expired!");
}
// Obtain the persistent tokens
// Create a client from temporary tokens
const client = new TwitterApi({
appKey: CONSUMER_KEY,
appSecret: CONSUMER_SECRET,
accessToken: oauth_token,
accessSecret: oauth_token_secret,
});
client.login(oauth_verifier)
.then(({ client: loggedClient, accessToken, accessSecret }) => {
// loggedClient is an authenticated client in behalf of some user
// Store accessToken & accessSecret somewhere
})
.catch(() => res.status(403).send("Invalid verifier or access tokens!"));
});
The above code doesn't work yet, because i do not have session set up, but i would prefer to first clear up my confusion about these tokens.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
