You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成X OAuth2授权时令牌交换遇JSON解析错误

React Native Expo Auth Session 调用Twitter OAuth2令牌接口返回浏览器不支持错误

问题背景

在React Native应用中基于expo-auth-session实现X(原Twitter)OAuth2授权流程,已成功获取授权码,但调用令牌交换接口时,无论直接用fetch还是expo-auth-session的exchangeCodeAsync,都返回HTML错误页,核心提示:

<h1>This browser is no longer supported.</h1>

错误原因

  1. 端点使用错误:当前用的https://twitter.com/i/oauth2/token是网页端授权端点,会对请求的User-Agent做浏览器兼容性检测,React Native请求的UA不符合要求,被拦截重定向到错误页。
  2. 请求格式不匹配:直接用fetch时,设置了Content-Type: application/json,但Twitter OAuth2令牌接口要求请求体必须是application/x-www-form-urlencoded格式。

解决方案

1. 替换为API专用端点

将令牌和撤销端点替换为Twitter官方提供的API专用地址,该端点不做浏览器UA检测:

const TWITTER_AUTHORIZATION_ENDPOINT = "https://twitter.com/i/oauth2/authorize";
// 替换为API专用令牌端点
const TWITTER_TOKEN_ENDPOINT = "https://api.twitter.com/2/oauth2/token";
// 替换为API专用撤销端点
const TWITTER_REVOCATION_ENDPOINT = "https://api.twitter.com/2/oauth2/revoke";

const discovery = {
  authorizationEndpoint: TWITTER_AUTHORIZATION_ENDPOINT,
  tokenEndpoint: TWITTER_TOKEN_ENDPOINT,
  revocationEndpoint: TWITTER_REVOCATION_ENDPOINT,
};

2. 修复直接fetch的请求格式

如果使用原生fetch交换令牌,需将请求体转为application/x-www-form-urlencoded格式:

async function exchangeAccessToken({ code, codeVerifier, redirectUri }) {
  const uri = TWITTER_TOKEN_ENDPOINT;
  const formData = new FormData();
  formData.append('code', code);
  formData.append('client_id', CLIENT_ID);
  formData.append('grant_type', 'authorization_code');
  formData.append('code_verifier', codeVerifier);
  formData.append('redirect_uri', redirectUri);

  const response = await fetch(uri, {
    method: "POST",
    body: formData,
  });

  const data = await response.json();
  return data;
}

3. 使用expo-auth-session的exchangeCodeAsync

替换端点后,原有的exchangeCodeAsync代码无需额外修改,库会自动处理正确的请求格式:

const exchangeAccessRequest = {
  clientId: CLIENT_ID,
  code,
  redirectUri,
  extraParams: {
    code_verifier: codeVerifier,
  },
};

const data = await AuthSession.exchangeCodeAsync(exchangeAccessRequest, discovery);

验证

修改完成后重新发起令牌交换请求,将正常返回JSON格式的令牌数据,不再出现浏览器不支持的错误页。

内容的提问来源于stack exchange,提问作者Victorio Jesús Molina Bermejo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 17:14:51