oauth2.0 错误:请求无效:为授权代码传递的值无效

oknwwptz  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(240)

我遵循了以下指南:

代码

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,
});

我是这样生成认证链接的

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();

点击生成的链接并授权后。我从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]);

然后验证代码。

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

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

但我得到如下错误

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

我该如何解决这个问题?你能看出我做错了什么吗?

bjg7j2ky

bjg7j2ky1#

我决定在授权步骤中放弃twitter-api-v2,只使用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);
}

不幸的是,我现在得到了一个不同但措辞相似的错误:Value passed for the token was invalid.

相关问题