twitteroauth-2.0oauthtwitter-oauthtwitter-api-v2

Error: Invalid Request: Value passed for the authorization code was invalid


I followed the following guides:

My code

Client.ts

import { TwitterApi } from "twitter-api-v2";
import { TWITTER_API_CLIENT_ID, TWITTER_API_CLIENT_SECRET } from "./constants";

export const client = new TwitterApi({
  clientId: TWITTER_API_CLIENT_ID,
  clientSecret: TWITTER_API_CLIENT_SECRET,
});

This is how I generate the auth link

const { url, codeVerifier } = twitterClient.generateOAuth2AuthLink(
      TWITTER_API_REDIRECT_URL,
      {
        scope: [
          "tweet.read",
          "tweet.write",
          "users.read",
          "offline.access",
          "follows.read",
        ],```

      }
    );

    await UserAPI.create({
        userId,
        codeVerifier,
        status: UserAPIStatus.PENDING,
      }).save();

After I click through the link generated and authorise. I get the auth code from the URL

const router = useRouter();
const authCode = router.query.code as string | undefined;
  useEffect(() => {
    if (me?.hasTwitterAccess) return;

    const fetch = async (authCode: string) => {
      await validateTwitterApiAccess({
        options: {
          authCode,
        },
      });
    };

    // TODO: fix in backend then dpeloy
    if (authCode) fetch(authCode);
  }, [fetching, authCode]);

I then verify the code.

const userAPI = await UserAPI.findOne({
      userId,
      type: UserAPIType.TWITTER,
    });

twitterClient.loginWithOAuth2({
        code: authCode,
        codeVerifier: userAPI.codeVerifier,
        redirectUri: TWITTER_API_REDIRECT_URL,
      })

But I get the following error

{
  error: 'invalid_request',
  error_description: 'Value passed for the authorization code was invalid.',
  errors: [ { code: 131, message: 'invalid_request' } ]
}

How do I resolve this? Can you spot if I'm doing something wrong?


Solution

  • I decided to abandon twitter-api-v2 for the authorisation step and just use axios.

    const options = {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
        },
        data: {
          code_verifier: codeVerifier,
          code,
          redirect_url: process.env.TWITTER_API_REDIRECT_URL,
          grant_type: "authorization_code",
          client_id: process.env.TWITTER_API_CLIENT_ID,
        },
        url: "https://api.twitter.com/2/oauth2/token",
      };
    
    let res = null
    try {
     res = await axios(options)
    } catch (error) {
        console.error("error.response.data", error.response);
    }
    

    Sadly, I now get a different but similarly worded error: Value passed for the token was invalid.