OAuth2 HTTP method alternatives
QtNetworkAuth provides HTTP Methods such as QAbstractOAuth::get() for issuing authenticated requests. In the case of OAuth2, this typically means setting the Authorization header, as specified in RFC 6750.
Since this operation is straightforward to do, it is better to use the normal QtNetwork HTTP method APIs directly, and set this header manually. These QtNetwork APIs have less assumptions on the message content types and provide a broader set of APIs.
See QRestAccessManager, QNetworkAccessManager, QNetworkRequest, QNetworkRequestFactory.
QNetworkRequest
The needed Authorization header can be set directly on each request needing 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);
After setting the header, use the request normally with either QRestAccessManager or QNetworkAccessManager.
QNetworkRequestFactory
QNetworkRequestFactory is a convenience class introduced in Qt 6.7. It provides a suitable method for this task: QNetworkRequestFactory::setBearerToken(), as illustrated by the code below.
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()); });
After setting the bearer token, use the request factory normally with either QRestAccessManager or QNetworkAccessManager.
© 2024 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.