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

Qt中QOAuth2AuthorizationCodeFlow添加duration参数失效问题求助

问题原因及解决方法

你的问题出在参数添加的阶段不对:Reddit要求duration=permanent参数必须附加在授权请求阶段(即引导用户跳转的授权URL),而不是你当前设置的「请求AccessToken」阶段。

Reddit的OAuth2流程中,duration参数是用来告诉授权服务器要返回长期有效的refresh_token,这个参数需要在用户第一次跳转授权页面时就传递,而不是后续用授权码换AccessToken的请求里。你之前的代码把参数加在了RequestingAccessToken阶段,这时候Reddit服务器根本不会读取这个参数,自然无法生成refresh_token。

修正后的代码

把修改参数的阶段改成QAbstractOAuth::Stage::RequestingAuthorization即可:

QOAuth2AuthorizationCodeFlow oauth2(this); // 补充缺失的对象定义

auto replyHandler = new QOAuthHttpServerReplyHandler(QHostAddress::Any, 1337, this);
oauth2.setReplyHandler(replyHandler);
oauth2.setAuthorizationUrl(QUrl("https://www.reddit.com/api/v1/authorize"));
oauth2.setTokenUrl(QUrl("https://www.reddit.com/api/v1/access_token"));
oauth2.setClientIdentifier(clientId);
const QSet<QByteArray> scope = {"identity", "read"};
oauth2.setRequestedScopeTokens(scope);

oauth2.setModifyParametersFunction([](QAbstractOAuth::Stage stage, QMultiMap<QString, QVariant> *parameters) {
    if (!parameters)
        return;

    // 关键:在授权请求阶段添加duration参数
    if (stage == QAbstractOAuth::Stage::RequestingAuthorization) {
        parameters->insert("duration", "permanent");
    }
});

额外注意事项

  • 确保你的Reddit应用设置中,重定向URI包含http://localhost:1337(和你的replyHandler端口一致),否则会授权失败
  • 如果你是桌面应用,Reddit应用类型要选择「installed app」,web应用选「web app」,不同类型的授权流程有细微差异
  • 授权成功后,通过oauth2.refreshToken()可以获取到返回的refresh_token,后续可以用它来刷新AccessToken

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:58:21