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

使用Tweepy OAuth2.0授权Twitter应用时遇授权失败及MissingCodeError

问题

尝试用Tweepy完成Twitter OAuth2.0授权时,跳转到授权URL后,Twitter页面提示:

Failed to grant access to the application. Try going back and logging in again.

同时后端抛出错误:

oauthlib.oauth2.rfc6749.errors.MissingCodeError: (missing_code) `Missing code parameter in response.`

使用的代码片段:

oauth2_user_handler = tweepy.OAuth2UserHandler(
    client_id=oauth_id,
    redirect_uri=callback_url,
    scope=["tweet.post", "tweet.read", "tweet.write", "users.read", "follows.read", "follows.write", "like.read", "like.write", "offline.access"],
    client_secret=oauth_secret
)

auth_link = oauth2_user_handler.get_authorization_url()

生成的授权URL示例:

https://twitter.com/i/oauth2/authorize?response_type=code&client_id=Q0ZxT3FyMzFsWlFHWkNoNHc5QjM6MTpjaQ&redirect_uri=https%3A%2F%2Fd7db-212-252-142-151.ngrok-free.app%2Fcallback&scope=tweet.post+tweet.read+tweet.write+users.read+follows.read+follows.write+like.read+like.write+offline.access&state=a0smv3ENkUJVcisbJNwnwuMf585N36&code_challenge=sNDSO0EWOR9pjN5vwRfhA59O2v28AS7vmArnGRPl5Yo&code_challenge_method=S256
解决思路
  • 检查Twitter开发者平台的应用配置

    1. 确保redirect_uri和开发者平台填写的地址完全一致,包括HTTP/HTTPS协议、末尾是否带斜杠等细节,比如你用的ngrok HTTPS地址,必须在应用的「User authentication settings」里的「Callback URI / Redirect URL」精确匹配。
    2. 核对「App permissions」和代码里的scope是否匹配:比如你请求了offline.access,要确认平台里开启了持久授权的相关选项;另外scope里tweet.write已经包含tweet.post的权限,重复请求可能触发授权异常,建议删掉tweet.post。
    3. 确认应用状态是「Enabled」,没有被Twitter限制或封禁。
  • 代码与流程排查

    1. 若你的应用是公共客户端(比如移动端),不要在OAuth2UserHandler中传入client_secret;如果是后端机密客户端,要确保PKCE流程配置正确,Tweepy默认生成PKCE挑战,需保证后续获取token时流程兼容。
    2. 检查回调路由的逻辑:用户授权后,Twitter会把code参数带到redirect_uri,后端必须正确捕获这个参数,再调用oauth2_user_handler.fetch_token(code=xxx),如果路由没正确传递code,就会抛出MissingCodeError。
  • 其他排查点

    1. 若用了ngrok动态域名,确认域名未过期,且已同步更新到开发者平台的redirect_uri。
    2. 尝试用浏览器隐身模式打开授权URL,清空缓存或禁用第三方Cookie,避免旧会话干扰。

内容的提问来源于stack exchange,提问作者Furkan Suren

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:20:11