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

无法获取Reddit OAuth access token,持续返回invalid_grant错误如何解决?

Reddit OAuth授权请求返回invalid_grant错误解决

问题背景

  • 技术栈:前端Vue.js、后端Node.js + Express、请求库Axios
  • 业务场景:开发信息汇总类Web应用,新增Reddit组件功能,此前已使用Kotlin基于Reddit API开发过可正常运行的应用,熟悉API与OAuth运行逻辑
  • 错误表现:Reddit授权回调后,后端使用临时授权码请求access_token时固定返回{ error: 'invalid_grant' },相同请求头和参数使用Postman发起可正常获取token

核心请求代码

async function getToken(uniqueCode) {
    let authString = `${client_id}:${client_secret}`;
    authString = Buffer.from(authString).toString('base64');

    let requestHeaders = {
        'Authorization': `Basic ${authString}`,
        'Content-Type': 'application/x-www-form-urlencoded'
    };

    const params = new URLSearchParams();
    params.append("grant_type", "authorization_code");
    params.append("code", uniqueCode);
    params.append("redirect_uri", "http://localhost:8081/oauth_callback");

    let res = await axios.post('https://www.reddit.com/api/v1/access_token', params, {headers: requestHeaders});

    return res.body.access_token
}

错误排查过程

  1. 首先核对请求配置:请求头、grant_type、redirect_uri参数均符合Reddit OAuth2官方文档要求,排除配置错误
  2. 观察Axios实际发出的请求日志:
headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: 'Basic {已脱敏}',
      'User-Agent': 'axios/0.24.0',
      'Content-Length': 129
    },
method: 'post',
url: 'https://www.reddit.com/api/v1/access_token',
data: 'grant_type=authorization_code&code=LiTC051x3nEKqXSbU0spuHgKHHaLGw%23_&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Foauth_callback'
  1. 解码请求参数中的授权码字段LiTC051x3nEKqXSbU0spuHgKHHaLGw%23_,发现末尾被编码的%23对应字符为#,即实际传入的授权码末尾多了#_冗余字符,该字符是Reddit授权回调时自动附加在URL末尾的,提取授权码时未做清理导致参数无效。application/x-www-form-urlencoded对特殊字符的编码属于规范行为,和本次错误无关。

解决方案

提取回调URL中的授权码时,先清理末尾冗余的#_字符即可,示例处理逻辑:

// 从回调URL参数中获取原始授权码后过滤冗余字符
const rawCode = new URLSearchParams(window.location.search).get('code')
const validCode = rawCode.replace(/#_$/, '')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:06:09