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

Google账户OAuth2刷新access_token失败及重定向问题求助

无法通过refresh_token刷新Gmail OAuth2 access_token的问题及解决

我在Google API控制台创建了项目,获取了client_id和client_secret,开发的是一款访问Gmail账户的邮件应用。通过Google OAuth2 Playground获取到refresh_token和access_token后,用该access_token生成认证字符串成功访问了Gmail账户,但access_token会在1小时后过期。

问题在于无法使用永久有效的refresh_token刷新access_token。使用OAuth2DotPy中的oauth2.py执行以下命令:

python3 oauth2.py --user=xxx@gmail.com \
 --client_id=111.apps.googleusercontent.com \
 --client_secret=XXX \
 --refresh_token=1//1/1/1//1

出现如下错误:

Traceback (most recent call last):
  File "/home/.../oauth2.py", line 353, in <module>
    main(sys.argv)
  File "/home/.../oauth2.py", line 312, in main
    response = RefreshToken(options.client_id, options.client_secret,
  File "/home/.../oauth2.py", line 247, in RefreshToken
    response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('utf-8')).read()
  File "/usr/lib/python3.10/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.10/urllib/request.py", line 525, in open
    response = meth(req, response)
  File "/usr/lib/python3.10/urllib/request.py", line 634, in http_response
    response = self.parent.error(
  File "/usr/lib/python3.10/urllib/request.py", line 563, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.10/urllib/request.py", line 496, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.10/urllib/request.py", line 643, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Unauthorized

*** 编辑1 ***
尝试用oauth2.py生成令牌,执行命令:

python3 oauth2.py --generate_oauth2_token --user=xxx@gmail.com \
 --client_id=11111.apps.googleusercontent.com \
 --client_secret=XXXXXXXX

返回内容:

To authorize token, visit this url and follow the directions:
  https://accounts.google.com/...%2F
Enter verification code: _

访问该URL后,Google提示Blocked Access : The request of this app is invalid以及Error 400: redirect_uri_mismatch

*** 编辑2 ***
在Google控制台中配置允许对应的OAuth2重定向地址后,问题解决。执行以下命令:

python3 oauth2.py --generate_oauth2_token --user=xxx@gmail.com \
 --client_id=XXX.... \
 --client_secret=XXX

成功获取验证码,输入到oauth2.py程序后得到了永久有效的refresh_token。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:40:27