OAuth2 HTTP 方法替代方案

QtNetworkAuth 提供 HTTP 方法,如 () 以发出验证请求。就 OAuth2 而言,这通常意味着设置 标头,如QAbstractOAuth::get Authorization RFC 6750 所规定。

由于这一操作简单明了,所以最好直接使用正常的QtNetwork HTTP 方法 API,并手动设置该标头。这些QtNetwork API 对消息内容类型的假设较少,并提供了更广泛的 API 集。

请参见QRestAccessManager,QNetworkAccessManager,QNetworkRequest,QNetworkRequestFactory

QNetworkRequest

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

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);

设置头之后,可通过QRestAccessManagerQNetworkAccessManager 正常使用请求。

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());
});

设置承载令牌后,可通过QRestAccessManagerQNetworkAccessManager 正常使用请求工厂。

© 2025 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.