QAbstractOAuth2 Class | Qt Network Authorization | Qt 6.11.2
Description: The QAbstractOAuth2 class is the base of all implementations of OAuth 2 authentication methods.

- Qt 6.11
- Qt Network Authorization
- C++ Classes
- QAbstractOAuth2
- Qt Network Authorization | Commercial or GPLv3

# QAbstractOAuth2 Class

The QAbstractOAuth2 class is the base of all implementations of OAuth 2 authentication methods. More...

Header: | `#include <QAbstractOAuth2>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS NetworkAuth)` `target_link_libraries(mytarget PRIVATE Qt6::NetworkAuth)`
qmake: | `QT += networkauth`
Inherits: | QAbstractOAuth
Inherited By: | QOAuth2AuthorizationCodeFlow and QOAuth2DeviceAuthorizationFlow

- List of all members, including inherited members
- Deprecated members

## Public Types

`(since 6.9)` enum class | NonceMode { Automatic, Enabled, Disabled }

## Properties

`(since 6.9)` autoRefresh : bool clientIdentifierSharedKey : QString expiration : QDateTime `(since 6.9)` grantedScopeTokens : QSet<QByteArray> `(since 6.9)` idToken : QString `(since 6.9)` nonce : QString `(since 6.9)` nonceMode : NonceMode | `(since 6.9)` refreshLeadTime : std::chrono::seconds refreshToken : QString `(since 6.9)` requestedScopeTokens : QSet<QByteArray> `(until 6.13)` scope : QString state : QString `(since 6.9)` tokenUrl : QUrl userAgent : QString

## Public Functions

| QAbstractOAuth2(QObject *parent = nullptr)
| QAbstractOAuth2(QNetworkAccessManager *manager, QObject *parent = nullptr)
virtual | ~QAbstractOAuth2()
bool | autoRefresh() const
void | clearNetworkRequestModifier()
QString | clientIdentifierSharedKey() const
virtual QUrl | createAuthenticatedUrl(const QUrl &url, const QVariantMap &parameters = QVariantMap())
QDateTime | expirationAt() const
QSet<QByteArray> | grantedScopeTokens() const
QString | idToken() const
QString | nonce() const
QAbstractOAuth2::NonceMode | nonceMode() const
std::chrono::seconds | refreshLeadTime() const
QString | refreshToken() const
QSet<QByteArray> | requestedScopeTokens() const
QString | responseType() const
QString | scope() const
void | setAutoRefresh(bool enable)
void | setClientIdentifierSharedKey(const QString &clientIdentifierSharedKey)
`(since 6.9)` void | setNetworkRequestModifier(const QAbstractOAuth2::ContextTypeForFunctor<Functor> *context, Functor &&callback)
void | setNonce(const QString &nonce)
void | setNonceMode(QAbstractOAuth2::NonceMode mode)
void | setRefreshLeadTime(std::chrono::seconds leadTime)
void | setRefreshToken(const QString &refreshToken)
void | setRequestedScopeTokens(const QSet<QByteArray> &tokens)
void | setScope(const QString &scope)
`(since 6.5)` void | setSslConfiguration(const QSslConfiguration &configuration)
void | setState(const QString &state)
void | setTokenUrl(const QUrl &tokenUrl)
void | setUserAgent(const QString &userAgent)
`(since 6.5)` QSslConfiguration | sslConfiguration() const
QString | state() const
QUrl | tokenUrl() const
QString | userAgent() const

## Reimplemented Public Functions

`(deprecated in 6.11)` virtual QNetworkReply * | deleteResource(const QUrl &url, const QVariantMap &parameters = QVariantMap()) override
`(deprecated in 6.11)` virtual QNetworkReply * | get(const QUrl &url, const QVariantMap &parameters = QVariantMap()) override
`(deprecated in 6.11)` virtual QNetworkReply * | head(const QUrl &url, const QVariantMap &parameters = QVariantMap()) override
`(deprecated in 6.11)` virtual QNetworkReply * | post(const QUrl &url, const QVariantMap &parameters = QVariantMap()) override
virtual void | prepareRequest(QNetworkRequest *request, const QByteArray &verb, const QByteArray &body = QByteArray()) override
`(deprecated in 6.11)` virtual QNetworkReply * | put(const QUrl &url, const QVariantMap &parameters = QVariantMap()) override

## Public Slots

`(since 6.9)` void | refreshTokens()

## Signals

`(since 6.9)` void | accessTokenAboutToExpire()
void | authorizationCallbackReceived(const QVariantMap &data)
void | autoRefreshChanged(bool enable)
void | clientIdentifierSharedKeyChanged(const QString &clientIdentifierSharedKey)
`(until 6.13)` void | error(const QString &error, const QString &errorDescription, const QUrl &uri)
void | expirationAtChanged(const QDateTime &expiration)
void | grantedScopeTokensChanged(const QSet<QByteArray> &tokens)
void | idTokenChanged(const QString &idToken)
void | nonceChanged(const QString &nonce)
void | nonceModeChanged(QAbstractOAuth2::NonceMode mode)
void | refreshLeadTimeChanged(std::chrono::seconds leadTime)
void | refreshTokenChanged(const QString &refreshToken)
void | requestedScopeTokensChanged(const QSet<QByteArray> &tokens)
void | scopeChanged(const QString &scope)
`(since 6.9)` void | serverReportedErrorOccurred(const QString &error, const QString &errorDescription, const QUrl &uri)
`(since 6.5)` void | sslConfigurationChanged(const QSslConfiguration &configuration)
void | stateChanged(const QString &state)
void | tokenUrlChanged(const QUrl &tokenUrl)
void | userAgentChanged(const QString &userAgent)

## Protected Slots

`(since 6.9)` void | refreshTokensImplementation()

## Detailed Description

The class defines the basic interface of the OAuth 2 authentication classes. By inheriting this class, you can create custom authentication methods using the OAuth 2 standard for different web services.

A description of how OAuth 2 works can be found in: The OAuth 2.0 Authorization Framework

## Member Type Documentation

### `[since 6.9]` enum class QAbstractOAuth2::NonceMode

List of available nonce modes.

Constant | Value | Description
--- | --- | ---
`QAbstractOAuth2::NonceMode::Automatic` | `0` | Nonce is sent if the requested scope contains `openid`. This is the default mode, and sends `nonce` only when it's relevant to OIDC authentication flows.
`QAbstractOAuth2::NonceMode::Enabled` | `1` | Nonce is sent during authorization stage.
`QAbstractOAuth2::NonceMode::Disabled` | `2` | Nonce is not sent during authorization stage. This disables OpenID Connect `id_token` replay protection.

This enum was introduced in Qt 6.9.

See also nonce and OAuth 2.0 Overview.

## Property Documentation

### `[since 6.9]` autoRefresh : bool

This property enables or disables automatic refresh of the access token.

This property enables or disables the automatic refresh of the access token. This is useful for applications that require uninterrupted authorization without user intervention.

If this property is `true`, refreshTokens() will be automatically called when the token is about to expire and a valid refreshToken exists.

This enumeration was introduced in Qt 6.9.

Access functions:

bool | autoRefresh() const
void | setAutoRefresh(bool enable)

Notifier signal:

void | autoRefreshChanged(bool enable)

See also refreshLeadTime and accessTokenAboutToExpire().

### clientIdentifierSharedKey : QString

This property holds the client shared key used as a password if the server requires authentication to request the token.

Access functions:

QString | clientIdentifierSharedKey() const
void | setClientIdentifierSharedKey(const QString &clientIdentifierSharedKey)

Notifier signal:

void | clientIdentifierSharedKeyChanged(const QString &clientIdentifierSharedKey)

### `[read-only]` expiration : QDateTime

This property holds the expiration time of the current access token. An invalid value means that the authorization server hasn't provided a valid expiration time.

Access functions:

QDateTime | expirationAt() const

Notifier signal:

void | expirationAtChanged(const QDateTime &expiration)

See also QDateTime::isValid().

### `[read-only, since 6.9]` grantedScopeTokens : QSet<QByteArray>

This property holds the scope granted by the authorization server.

The requested and granted scope may differ. End-user may have opted to grant only a subset of the scope, or server-side policies may change it. The application should be prepared to handle this scenario, and check the granted scope to see if it should impact the application logic.

The server may omit indicating the granted scope altogether, as defined by RFC 6749. In this case the implementation assumes the granted scope is the same as the requested scope.

This enumeration was introduced in Qt 6.9.

Access functions:

QSet<QByteArray> | grantedScopeTokens() const

Notifier signal:

void | grantedScopeTokensChanged(const QSet<QByteArray> &tokens)

See also QAbstractOAuth2::requestedScopeTokens.

### `[read-only, since 6.9]` idToken : QString

This property holds the received OpenID Connect ID token.

This enumeration was introduced in Qt 6.9.

Access functions:

QString | idToken() const

Notifier signal:

void | idTokenChanged(const QString &idToken)

See also NonceMode, nonce, and Qt OpenID Connect Support.

### `[since 6.9]` nonce : QString

This property holds the string sent to the server during authentication. The nonce is used to associate applicable token responses (OpenID Connect `id_token` in particular) with the authorization stage.

The primary purpose of the `nonce` is to mitigate replay attacks. It ensures that the token responses received are in response to the authentication requests initiated by the application, preventing attackers from reusing tokens in unauthorized contexts. Therefore, it's important to include nonce verification as part of the token validation.

In practice, authorization server vendors may refuse the OpenID Connect request if a nonce isn't provided in the Authorization request.

The token itself is an opaque string, and should contain only URL-safe characters for maximum compatibility. Further the token must provide adequate entropy so that it's unguessable to attackers. There are no strict size limits for nonce, and authorization server vendors may impose their own minimum and maximum sizes.

While the `nonce` can be set manually, Qt classes will generate a 32-character nonce when needed if one isn't set.

This enumeration was introduced in Qt 6.9.

Access functions:

QString | nonce() const
void | setNonce(const QString &nonce)

Notifier signal:

void | nonceChanged(const QString &nonce)

See also nonceMode and Qt OpenID Connect Support.

### `[since 6.9]` nonceMode : NonceMode

This property holds the current nonce mode (whether or not nonce is used).

This enumeration was introduced in Qt 6.9.

Access functions:

QAbstractOAuth2::NonceMode | nonceMode() const
void | setNonceMode(QAbstractOAuth2::NonceMode mode)

Notifier signal:

void | nonceModeChanged(QAbstractOAuth2::NonceMode mode)

See also NonceMode and nonce.

### `[since 6.9]` refreshLeadTime : std::chrono::seconds

This property defines how far in advance accessTokenAboutToExpire() signal is emitted relative to the access token's expiration.

This property specifies the time interval (in seconds) before the current access token’s expiration, when accessTokenAboutToExpire() signal is emitted. The value set for this property must be a positive duration.

This interval allows the application to refresh the token well in advance, ensuring continuous authorization without interruptions.

If this property is not explicitly set, or the provided leadTime is larger than the token's lifetime, the leadTime defaults to 5% of the token's remaining lifetime, but not less than 10 seconds ahead of expiration (leaving time for the refresh request to complete).

Note: Expiration signal only works if the authorization server has provided a proper expiration time.

This enumeration was introduced in Qt 6.9.

Access functions:

std::chrono::seconds | refreshLeadTime() const
void | setRefreshLeadTime(std::chrono::seconds leadTime)

Notifier signal:

void | refreshLeadTimeChanged(std::chrono::seconds leadTime)

See also autoRefresh.

### refreshToken : QString

This property holds the refresh token used to obtain new access tokens.

Refresh tokens usually have longer lifespans than access tokens, so it makes sense to save them for later use.

Access functions:

QString | refreshToken() const
void | setRefreshToken(const QString &refreshToken)

Notifier signal:

void | refreshTokenChanged(const QString &refreshToken)

See also setRefreshToken().

### `[since 6.9]` requestedScopeTokens : QSet<QByteArray>

This property holds the desired scope which defines the permissions requested by the client.

Note: Scope tokens are limited to a subset of printable US-ASCII characters. Using characters outside this range is not supported.

This enumeration was introduced in Qt 6.9.

Access functions:

QSet<QByteArray> | requestedScopeTokens() const
void | setRequestedScopeTokens(const QSet<QByteArray> &tokens)

Notifier signal:

void | requestedScopeTokensChanged(const QSet<QByteArray> &tokens)

See also QAbstractOAuth2::grantedScopeTokens.

### `[until 6.13]` scope : QString

This enumeration is scheduled for deprecation in version 6.13.

Use requestedScopeTokens and grantedScopeTokens properties instead. This property will be removed in Qt 7.

This property holds the desired scope which defines the permissions requested by the client.

The scope value is updated to the scope value granted by the authorization server. In case of an empty scope response, the requested scope is assumed as granted and does not change.

The fact that this property serves two different roles, first as the requested scope and later as the granted scope, is an historical artefact. All new code is recommended to use QAbstractOAuth2::requestedScopeTokens and QAbstractOAuth2::grantedScopeTokens.

Access functions:

QString | scope() const
void | setScope(const QString &scope)

Notifier signal:

void | scopeChanged(const QString &scope)

See also QAbstractOAuth2::grantedScopeTokens and QAbstractOAuth2::requestedScopeTokens.

### state : QString

This property holds the string sent to the server during authentication. The state is used to identify and validate the request when the callback is received.

If no state has been set when the authorization flow starts, a random 32-character state is generated automatically. This is the default and the recommended way.

This state is the primary protection against cross-site request forgery, and should therefore contain a sufficient amount of randomness. If you set it manually consider using at least 32 random characters.

Certain characters are illegal in the state element (see RFC 6749). The use of illegal characters could lead to an unintended state mismatch and a failing OAuth 2 authorization. Therefore, if you attempt to set a value that contains illegal characters, the state is ignored and a warning is logged.

Access functions:

QString | state() const
void | setState(const QString &state)

Notifier signal:

void | stateChanged(const QString &state)

### `[since 6.9]` tokenUrl : QUrl

This property holds the token endpoint URL which is used to obtain tokens. Depending on the use case and authorization server support, these tokens can be access tokens, refresh tokens, and ID tokens.

Tokens are typically retrieved once the authorization stage is completed, and the token endpoint can also be used to refresh tokens as needed.

For example, QOAuth2AuthorizationCodeFlow uses this url to issue an access token request, and QOAuth2DeviceAuthorizationFlow uses this url to poll for an access token.

This enumeration was introduced in Qt 6.9.

Access functions:

QUrl | tokenUrl() const
void | setTokenUrl(const QUrl &tokenUrl)

Notifier signal:

void | tokenUrlChanged(const QUrl &tokenUrl)

### userAgent : QString

This property holds the User-Agent header used to create the network requests.

The default value is "QtOAuth/1.0 (+https://www.qt.io)".

Access functions:

QString | userAgent() const
void | setUserAgent(const QString &userAgent)

Notifier signal:

void | userAgentChanged(const QString &userAgent)

## Member Function Documentation

### `[explicit]` QAbstractOAuth2::QAbstractOAuth2(QObject *parent = nullptr)

Constructs a QAbstractOAuth2 object using parent as parent.

### `[explicit]` QAbstractOAuth2::QAbstractOAuth2(QNetworkAccessManager *manager, QObject *parent = nullptr)

Constructs a QAbstractOAuth2 object using parent as parent and sets manager as the network access manager.

### `[virtual noexcept]` QAbstractOAuth2::~QAbstractOAuth2()

Destroys the QAbstractOAuth2 instance.

### `[signal, since 6.9]` void QAbstractOAuth2::accessTokenAboutToExpire()

The signal is emitted when the access token is about to expire.

Emitting this signal requires that the access token has a valid expiration time. An alternative for handling this signal manually is to use autoRefresh.

This function was introduced in Qt 6.9.

See also refreshLeadTime, autoRefresh, and refreshTokens().

### `[signal]` void QAbstractOAuth2::authorizationCallbackReceived(const QVariantMap &data)

Signal emitted when the reply server receives the authorization callback from the server: data contains the values received from the server.

### void QAbstractOAuth2::clearNetworkRequestModifier()

Clears the network request modifier.

See also setNetworkRequestModifier().

### `[virtual invokable]` QUrl QAbstractOAuth2::createAuthenticatedUrl(const QUrl &url, const QVariantMap &parameters = QVariantMap())

The returned URL is based on url, combining it with the given parameters and the access token.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

### `[signal, until 6.13]` void QAbstractOAuth2::error(const QString &error, const QString &errorDescription, const QUrl &uri)

This function is scheduled for deprecation in version 6.13.

Use serverReportedErrorOccurred instead

Signal emitted when the server responds to the authorization request with an error as defined in RFC 6749 error response.

error is the name of the error; errorDescription describes the error and uri is an optional URI containing more information about the error.

See also QAbstractOAuth::requestFailed() and QAbstractOAuth2::serverReportedErrorOccurred().

### `[override virtual]` void QAbstractOAuth2::prepareRequest(QNetworkRequest *request, const QByteArray &verb, const QByteArray &body = QByteArray())

Reimplements: QAbstractOAuth::prepareRequest(QNetworkRequest *request, const QByteArray &verb, const QByteArray &body).

### QString QAbstractOAuth2::refreshToken() const

Gets the current refresh token.

Refresh tokens usually have longer lifespans than access tokens, so it makes sense to save them for later use.

Returns the current refresh token or an empty string, if there is no refresh token available.

Note: Getter function for property refreshToken.

See also setRefreshToken().

### `[slot, since 6.9]` void QAbstractOAuth2::refreshTokens()

Call this function to refresh the tokens. The function calls refreshTokensImplementation() to perform the actual refresh.

This function was introduced in Qt 6.9.

See also refreshTokensImplementation() and autoRefresh.

### `[protected slot, since 6.9]` void QAbstractOAuth2::refreshTokensImplementation()

This slot is called by refreshTokens() to send the token refresh request.

The derived classes should reimplement this slot to support token refreshing:

     class MyClass : public QAbstractOAuth2
     {
         ...
     protected Q_SLOTS:
         void refreshTokensImplementation() QT7_ONLY(override);
     };

     void MyClass::refreshTokensImplementation()
     {
         qDebug("refresh");
     }

This function was introduced in Qt 6.9.

See also autoRefresh and accessTokenAboutToExpire().

### QString QAbstractOAuth2::responseType() const

Returns the response_type used.

### `[signal, since 6.9]` void QAbstractOAuth2::serverReportedErrorOccurred(const QString &error, const QString &errorDescription, const QUrl &uri)

Signal emitted when the server responds to the authorization request with an error as defined in RFC 6749 error response.

error is the name of the error; errorDescription describes the error and uri is an optional URI containing more information about the error.

To catch all errors, including these RFC defined errors, with a single signal, use QAbstractOAuth::requestFailed().

This function was introduced in Qt 6.9.

### `[since 6.9]` template <typename Functor, QAbstractOAuth2::if_compatible_callback<Functor> = true> void QAbstractOAuth2::setNetworkRequestModifier(const QAbstractOAuth2::ContextTypeForFunctor<Functor> *context, Functor &&callback)

Sets the network request modification function to callback. This function is used to customize the network requests sent to the server.

callback has to implement the signature `void(QNetworkRequest&, QAbstractOAuth::Stage)`. The provided QNetworkRequest can be directly modified, and it is used right after the callback finishes. callback can be a function pointer, lambda, member function, or any callable object. The provided QAbstractOAuth::Stage can be used to check to which stage the request relates to (token request, token refresh request, or authorization request in case of QOAuth2DeviceAuthorizationFlow).

context controls the lifetime of the calls, and prevents access to de-allocated resources in case context is destroyed. In other words, if the object provided as context is destroyed, callbacks won't be executed. context must point to a valid QObject (and in case the callback is a member function, it needs to actually have it). Since the callback's results are used immediately, context must reside in the same thread as the QAbstractOAuth2 instance.

This function was introduced in Qt 6.9.

See also clearNetworkRequestModifier() and QNetworkRequest.

### void QAbstractOAuth2::setRefreshToken(const QString &refreshToken)

Sets the new refresh token refreshToken to be used.

A custom refresh token can be used to refresh the access token via this method and then the access token can be refreshed via refreshTokens().

Note: Setter function for property refreshToken.

See also refreshToken().

### `[since 6.5]` void QAbstractOAuth2::setSslConfiguration(const QSslConfiguration &configuration)

Sets the TLS configuration to be used when establishing a mutual TLS connection between the client and the Authorization Server.

This function was introduced in Qt 6.5.

See also sslConfiguration() and sslConfigurationChanged().

### `[since 6.5]` QSslConfiguration QAbstractOAuth2::sslConfiguration() const

Returns the TLS configuration to be used when establishing a mutual TLS connection between the client and the Authorization Server.

This function was introduced in Qt 6.5.

See also setSslConfiguration() and sslConfigurationChanged().

### `[signal, since 6.5]` void QAbstractOAuth2::sslConfigurationChanged(const QSslConfiguration &configuration)

The signal is emitted when the TLS configuration has changed. The configuration parameter contains the new TLS configuration.

This function was introduced in Qt 6.5.

See also sslConfiguration() and setSslConfiguration().