Twitter Ouath - Value passed for the redirect uri did not match the uri

46 Views Asked by At

When I try and configure the ouath authorization of twitter I get the Authorize App page here

enter image description here

When I click authorize app the redirect makes it to my callback endpoint, but I get

{
    "type": "response",
    "code": 400,
    "error": {
        "error": "invalid_request",
        "error_description": "Value passed for the redirect uri did not match the uri of the authorization code.",
        "errors": [
            {
                "code": 131,
                "message": "invalid_request"
            }
        ]
    },

The redirectUri I have in the twitter developer console here is identical to what i have in the code. No trailing slashes or anything. It's verbatim

enter image description here

import { APIGatewayProxyEvent, APIGatewayProxyHandler } from "aws-lambda";
import { TwitterApi } from "twitter-api-v2";

const twitterClient = new TwitterApi({
  clientId: "<my-client-id>",
  clientSecret: "my-client-scret>",
});


export async function redirectToTwitterAuth(event: APIGatewayProxyEvent) {
  const redirectUri =
    "https://<url>.execute-api.us-east-1.amazonaws.com/staging/social-media/oauth/twitter-callback";

  const { url, codeVerifier, state } = twitterClient.generateOAuth2AuthLink(
    redirectUri,
    {
      scope: ["tweet.read", "tweet.write", "users.read", "offline.access"], // Ensure these scopes align with Twitter's documentation.
    }
  );

  console.log("URL", url);

  return {
    statusCode: 302,
    headers: {
      Location: url,
    },
    body: url,
  };
}

How can I get passed this error. It says Value passed for the redirect uri did not match the uri of the authorization code but redirectUri is literally the exact same.

I also tried the getTwitterOauthUrl() instead in my code

function getTwitterOauthUrl() {
  const rootUrl = "https://twitter.com/i/oauth2/authorize";
  const options = {
    redirect_uri: callbackUrl1,
    client_id: "<my-client-id>",
    state: "state",
    response_type: "code",
    code_challenge: "y_SfRG4BmOES02uqWeIkIgLQAlTBggyhgf_G7uKT5d1ku8",
    code_challenge_method: "S256",
    scope: ["users.read", "tweet.read", "follows.read", "follows.write"].join(
      " "
    ), 
  };
  const qs = new URLSearchParams(options).toString();
  return `${rootUrl}?${qs}`;
}

and it gets me to authorize app screen too, but same issue.

I tried encoding the redirectUri ie encodeURI(redirectUri) and it makes it to Authorize App, but same error. If I do encodeURIComponent(redirectUri) then it doesn't even make that far. I appreciate any help!

0

There are 0 best solutions below