0

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 the oauth_token and oauth_token_secret for 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.

  • could possibly help if you showed your code rather than discuss the abstract concepts of OAuth2 which can be easily understood by reading documetation – Bravo May 15 '22 at 06:23
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan May 15 '22 at 06:41
  • @Bravo i have updated the post with my code. I hope you can help me! – Ranvir Choudhary May 15 '22 at 07:18

0 Answers0