本页内容

OAuth2 HTTP 方法替代方案

QtNetworkAuth 提供了诸如QAbstractOAuth::get() 等 HTTP 方法,用于发出经过身份验证的请求。在 OAuth2 场景下,这通常意味着需要按照RFC 6750 的规定设置Authorization 请求头。

由于此操作非常简单,建议直接使用常规的QtNetwork HTTP 方法 API,并手动设置该标头。这些QtNetwork API 对消息内容类型的限制较少,并提供了更全面的 API 集合。

参见QRestAccessManager 、QNetworkAccessManager 、QNetworkRequest 、QNetworkRequestFactory 。

QNetworkRequest

所需的Authorization头可以直接设置在每个需要授权的请求上。

using namespace Qt::StringLiterals;

QOAuth2AuthorizationCodeFlow m_oauth;
QNetworkRequest request;

QHttpHeaders headers;
headers.append(QHttpHeaders::WellKnownHeader::Authorization, u"Bearer "_s + m_oauth.token());
request.setHeaders(headers);

设置完标头后,即可通过QRestAccessManager 或QNetworkAccessManager 正常使用该请求。

QNetworkRequestFactory

QNetworkRequestFactory 是 Qt 6.7 中引入的一个便捷类。它为此任务提供了一个合适的方法:QNetworkRequestFactory::setBearerToken(),如下面的代码所示。

QNetworkRequestFactory m_api({"https://www.example.com/v3"});
QOAuth2AuthorizationCodeFlow m_oauth;
// ...
connect(&m_oauth, &QOAuth2AuthorizationCodeFlow::granted, this, [this]{
    m_api.setBearerToken(m_oauth.token().toLatin1());
});

设置承载令牌后,可像往常一样使用请求工厂,通过QRestAccessManager 或QNetworkAccessManager 进行调用。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.