Amber Web Authorization Framework
API DocumentationOAuth2 Class
(Amber::Web::Authorization::OAuth2)Provides a helper to allow applications to integrate OAuth2 flows. More...
Header: | #include <OAuth2> |
Instantiated By: | OAuth2 |
Public Types
enum | FlowType { InvalidFlow, ImplicitFlow, ClientCredentialsFlow, AuthorizationCodeFlow, AuthorizationCodeWithPkceFlow, ResourceOwnerPasswordFlow } |
Properties
|
|
Public Functions
OAuth2(QObject *parent = nullptr) | |
~OAuth2() | |
bool | abortCurrentRequest() |
QString | authorizationEndpoint() const |
QString | clientId() const |
QString | clientSecret() const |
QString | codeChallenge() const |
QString | codeChallengeMethod() const |
QString | codeVerifier() const |
QVariantMap | customParameters() const |
Amber::Web::Authorization::Error | error() const |
FlowType | flowType() const |
QUrl | generateAuthorizationUrl() |
QString | generateCodeVerifier() const |
QString | generateScope(const QStringList &scopes, const QString &separator) const |
QString | generateState() const |
QList<QSslError> | ignorableSslErrors() const |
QNetworkAccessManager * | networkAccessManager() const |
QVariantMap | parseRedirectUri(const QString &redirectUri) |
QString | redirectUri() const |
void | refreshAccessToken(const QString &refreshToken) |
QString | refreshEndpoint() const |
void | requestAccessToken(const QString &code = QString(), const QString &state = QString()) |
QString | scope() const |
void | setAuthorizationEndpoint(const QString &endpoint) |
void | setClientId(const QString &clientId) |
void | setClientSecret(const QString &clientSecret) |
void | setCodeVerifier(const QString &verifier) |
void | setCustomParameters(const QVariantMap ¶meters) |
void | setFlowType(FlowType flow) |
void | setIgnorableSslErrors(const QList<QSslError> &errors) |
void | setNetworkAccessManager(QNetworkAccessManager *manager) |
void | setRedirectUri(const QString &uri) |
void | setRefreshEndpoint(const QString &endpoint) |
void | setScope(const QString &scope) |
void | setScope(const QStringList &scopes, const QString &separator = QString::fromLatin1( "," )) |
void | setState(const QString &state) |
void | setTokenEndpoint(const QString &endpoint) |
void | setUserAgent(const QString &ua) |
QString | state() const |
QString | tokenEndpoint() const |
QString | userAgent() const |
Signals
void | authorizationEndpointChanged() |
void | clientIdChanged() |
void | clientSecretChanged() |
void | codeChallengeChanged() |
void | codeChallengeMethodChanged() |
void | codeVerifierChanged() |
void | customParametersChanged() |
void | errorChanged() |
void | flowTypeChanged() |
void | ignorableSslErrorsChanged() |
void | networkAccessManagerChanged() |
void | receivedAccessToken(const QVariantMap &token) |
void | redirectParseError(const QString &errorMessage) |
void | redirectUriChanged() |
void | refreshEndpointChanged() |
void | scopeChanged() |
void | sslErrors(const QList<QSslError> &errors) |
void | stateChanged() |
void | tokenEndpointChanged() |
void | userAgentChanged() |
Detailed Description
Provides a helper to allow applications to integrate OAuth2 flows.
Applications can use an instance of this type to retrieve an access token from an OAuth2-enabled remote service (such as Google).
Note: QML applications will most likely use one of the flow-specific helper types (e.g. OAuth2AcPkce
) rather than using this type directly, so this class is mostly of interest to C++ applications or applications which make use of an unusual OAuth2 flow.
See also amberwebauthcppexample and amberwebauthqmlexample.
Member Type Documentation
enum OAuth2::FlowType
This enum defines the OAuth2 flow types supported by the helper.
Most client applications should use the AuthorizationCodeWithPkceFlow
type, as it does not require the user to trust the application (as the authorization step is done via the system web browser).
Constant | Value | Description |
---|---|---|
Amber::Web::Authorization::OAuth2::InvalidFlow | 0 | An invalid or unknown OAuth2 flow |
Amber::Web::Authorization::OAuth2::ImplicitFlow | 1 | A legacy OAuth2 flow (deprecated, should not be used by new clients) |
Amber::Web::Authorization::OAuth2::ClientCredentialsFlow | 2 | A machine-to-machine grant, where the requester is the resource owner |
Amber::Web::Authorization::OAuth2::AuthorizationCodeFlow | 3 | For web-apps running on a trusted web-server |
Amber::Web::Authorization::OAuth2::AuthorizationCodeWithPkceFlow | 4 | For most apps running on a device |
Amber::Web::Authorization::OAuth2::ResourceOwnerPasswordFlow | 5 | For trusted client apps, where the user provides the app their credentials |
Property Documentation
authorizationEndpoint : QString
This property holds this property holds the "authorization endpoint" OAuth2 parameter which should be used by the helper when generating an authorization URL which will then be opened in the system browser, which allows the user to authorize the application.
Once successful, the browser will be redirected to the location specified by the redirectUri property, with query parameters which include the verifier code for the temporary token.
It must be a full, valid URL which is specified by the remote service, e.g. https://accounts.google.com/o/oauth2/auth
.
It is a mandatory property.
Access functions:
QString | authorizationEndpoint() const |
void | setAuthorizationEndpoint(const QString &endpoint) |
Notifier signal:
void | authorizationEndpointChanged() |
clientId : QString
This property holds this property holds the "client_id" OAuth2 parameter which is associated with the client application.
It is a mandatory property.
Access functions:
QString | clientId() const |
void | setClientId(const QString &clientId) |
Notifier signal:
void | clientIdChanged() |
clientSecret : QString
This property holds this property holds the "client_secret" OAuth2 parameter which is associated with the client application.
It is a mandatory property.
Access functions:
QString | clientSecret() const |
void | setClientSecret(const QString &clientSecret) |
Notifier signal:
void | clientSecretChanged() |
codeChallenge : const QString
This property holds this property holds the "code_challenge" OAuth2 parameter which is sent to the remote server for type flows.
The codeChallenge
value is automatically generated (via secure hash) from the codeVerifier
specified by the client.
Clients generally do not need to care about this value themselves, as the helper will generate and send it as appropriate during the flow.
Access functions:
QString | codeChallenge() const |
Notifier signal:
void | codeChallengeChanged() |
See also codeVerifier().
codeChallengeMethod : const QString
This property holds this property holds the "code_challenge_method" OAuth2 parameter which is sent to the remote server for type flows.
The codeChallengeMethod
value is always "S256"
currently as that is the only hashing method which the helper currently supports.
Clients generally do not need to care about this value themselves, as the helper will generate and send it as appropriate during the flow.
Access functions:
QString | codeChallengeMethod() const |
Notifier signal:
void | codeChallengeMethodChanged() |
See also codeChallenge().
codeVerifier : QString
This property holds this property holds the "verifier" OAuth2 parameter which is required for type flows.
It should contain a cryptographically random string, and clients should generally set this property to the value returned by generateCodeVerifier().
It is a mandatory property for AuthorizationCodeWithPkceFlow
flows.
Access functions:
QString | codeVerifier() const |
void | setCodeVerifier(const QString &verifier) |
Notifier signal:
void | codeVerifierChanged() |
See also generateCodeVerifier().
customParameters : QVariantMap
This property holds this property holds the custom parameters which should be included as query parameters in the next request to the server.
It is a dictionary of key/value pairs, where both the key and value must be strings.
Some services allow (or sometimes, require) clients to pass non-standard parameters at various points in the OAuth2 flow, and this property allows the client to specify appropriate values for such parameters.
It is an optional property.
Access functions:
QVariantMap | customParameters() const |
void | setCustomParameters(const QVariantMap ¶meters) |
Notifier signal:
void | customParametersChanged() |
error : const Amber::Web::Authorization::Error
This property holds this property holds information associated with the most recent operation error encountered by the helper.
The possible values of the error code are described here.
In general, if any error (other than NoError
) occurs, then the flow has failed for some reason.
Access functions:
Amber::Web::Authorization::Error | error() const |
Notifier signal:
void | errorChanged() |
flowType : FlowType
This property holds this property holds the specific OAuth2 flow type which the client application will use.
Most clients should use the AuthorizationCodeWithPkceFlow
type.
Access functions:
FlowType | flowType() const |
void | setFlowType(FlowType flow) |
Notifier signal:
void | flowTypeChanged() |
ignorableSslErrors : QList<QSslError>
This property holds this property holds the SSL errors which should be ignored if encountered in the next request to the server.
If a request fails due to an SSL error, the user can be shown the errors and given the opportunity to allow the operation to continue (e.g. if they know that the server is safe, despite using a self-signed certificate, etc). If the user allows it, the application can then set this property to contain the errors which were encountered, and then retry the request (which should then succeed, as it will ignore the specified errors). Note that the application should then set this property to an empty list value, to avoid accidentally ignoring future errors.
This property is difficult to use properly from a QML context, as the QSslError
type is opaque to QML; as such, this property is mostly useful for C++ clients.
It is an optional property.
Access functions:
QList<QSslError> | ignorableSslErrors() const |
void | setIgnorableSslErrors(const QList<QSslError> &errors) |
Notifier signal:
void | ignorableSslErrorsChanged() |
See also sslErrors().
networkAccessManager : QNetworkAccessManager *
This property holds this property holds the network access manager instance which will be used when performing requests to the server.
If the client does not provide a specific network access manager to use, a default-constructed network access manager will be creating when performing the first request, and set as the value of this property.
Most clients will not usually need to provide a network access manager, but it might be useful if custom headers need to be provided to the remote service during requests.
If the client provides the network access manager, it retains ownership of it, and must delete it after the OAuth2 instance is deleted (or set its QObject parent to be the OAuth2 instance) to avoid leaking memory.
It is an optional property.
Access functions:
QNetworkAccessManager * | networkAccessManager() const |
void | setNetworkAccessManager(QNetworkAccessManager *manager) |
Notifier signal:
void | networkAccessManagerChanged() |
redirectUri : QString
This property holds this property holds the redirect URI to which the system browser will be redirected once the authorization step of the flow is complete.
If the client application is using a RedirectListener to listen for that redirect, then this property should be bound the uri
property of the RedirectListener instance.
Otherwise, if the client application is using some other mechanism to listen for redirects, it should set this property value to the appropriate redirect URI value (which the client application is able to handle).
It is a mandatory property.
Access functions:
QString | redirectUri() const |
void | setRedirectUri(const QString &uri) |
Notifier signal:
void | redirectUriChanged() |
refreshEndpoint : QString
This property holds this property holds the "refresh endpoint" OAuth2 parameter which should be used by the helper in order to request a refreshed access token given a valid refresh token.
It must be a full, valid URL which is specified by the remote service, e.g. https://accounts.google.com/o/oauth2/token
.
If no value is specified for this property, the helper will attempt to use the tokenEndpoint
as the refresh endpoint.
Most clients will never need to set this property, as by default the refresh endpoint should be identical to the token endpoint. Clients will only need to set this property if the service with which they interact does not conform to the OAuth2 specification.
It is an optional property.
Access functions:
QString | refreshEndpoint() const |
void | setRefreshEndpoint(const QString &endpoint) |
Notifier signal:
void | refreshEndpointChanged() |
scope : QString
This property holds this property holds the "scope" OAuth2 parameter which defines the types of resources or operations to which the application is requesting access.
Different services may require this to be formatted in different ways, e.g. with different separators, if the scope is a list of values.
It is a mandatory property.
Access functions:
QString | scope() const |
void | setScope(const QString &scope) |
void | setScope(const QStringList &scopes, const QString &separator = QString::fromLatin1( "," )) |
Notifier signal:
void | scopeChanged() |
See also generateScope().
state : QString
This property holds this property holds the "state" OAuth2 parameter which helps to prevent certain types of integrity attacks during the authorization process.
It should contain a cryptographically random string, and clients should generally set this property to the value returned by generateState().
It is an optional property.
Access functions:
QString | state() const |
void | setState(const QString &state) |
Notifier signal:
void | stateChanged() |
See also generateState().
tokenEndpoint : QString
This property holds this property holds the "token endpoint" OAuth2 parameter which should be used by the helper in order to request an access token.
It must be a full, valid URL which is specified by the remote service, e.g. https://accounts.google.com/o/oauth2/token
.
It is a mandatory property.
Access functions:
QString | tokenEndpoint() const |
void | setTokenEndpoint(const QString &endpoint) |
Notifier signal:
void | tokenEndpointChanged() |
userAgent : QString
This property holds this property holds the user agent string which should be specified in the request headers when performing the authorization flow.
It is an optional property.
Access functions:
QString | userAgent() const |
void | setUserAgent(const QString &ua) |
Notifier signal:
void | userAgentChanged() |
Member Function Documentation
OAuth2::OAuth2(QObject *parent = nullptr)
Constructs a new OAuth2 helper instance, with the specified QObject parent.
OAuth2::~OAuth2()
Destroys the OAuth2 helper instance
bool OAuth2::abortCurrentRequest()
Aborts the current ongoing network request, if possible.
Returns true if there is a current ongoing network request which was able to be aborted, otherwise returns false.
QUrl OAuth2::generateAuthorizationUrl()
Build an authorization URL to be displayed in the system web browser.
The first step in an ImplicitFlow
, AuthorizationCodeFlow
, or AuthorizationCodeWithPkceFlow
is to allow the user to authorize (or deny authorization for) the application, which is performed via the system web browser. The client application must generate an appropriate authorization URL (which contains parameters identifying the application and the scope of access being requested).
After setting the appropriate properties on the helper, the client may call this method to generate the URL. This URL can then be displayed in the system web browser, and if the user authorizes the application accordingly, the web browser will be redirected to the URI specified in the redirectUri property, with a verifier code included as a query parameter.
On success, this method returns a valid URL.
Otherwise, an invalid URL is returned, and the error property will be set, and the errorChanged() signal will be emitted.
QString OAuth2::generateCodeVerifier() const
Generates cryptographically-secure random data for use as the codeVerifier
property value
QString OAuth2::generateScope(const QStringList &scopes, const QString &separator) const
Joins the specified scopes with the specified separator and returns the result as a valid scope
string
QString OAuth2::generateState() const
Generates cryptographically-secure random data for use as the state
property value
QVariantMap OAuth2::parseRedirectUri(const QString &redirectUri)
Parse the given redirectUri and construct a map of key/value pairs.
Both the URI fragment and the query parameters will be parsed, and the key/value pairs will be inserted into the returned dictionary.
The client can then look for the existence of appropriate entries (e.g. "error", "code", "access_token", etc.
Any errors encountered during parsing are assumed to be non-fatal, and so while the redirectParseError signal will be emitted, the error will not be set.
The client must determine whether the flow has failed, for example by determining whether the output contains the appropriate token.
[signal]
void OAuth2::receivedAccessToken(const QVariantMap &token)
This signal is emitted when the helper receives an access token from the remote service.
The token will be a dictionary of key/value pairs which should include the "access_token"
but may also include other values, including "expires_in"
and "refresh_token"
depending on the flow used.
See also requestAccessToken().
[signal]
void OAuth2::redirectParseError(const QString &errorMessage)
This signal is emitted if the helper encounters a (possibly non-fatal) error while parsing the redirect
void OAuth2::refreshAccessToken(const QString &refreshToken)
Request a refreshed access token from the server
If the client application has received a refresh token from the server, it can request a refreshed access token periodically without requiring further user interaction.
This method allows the client application to trigger such a request with the remote server, by providing the previously returned refreshToken.
The request will be directed to the refreshEndpoint if a value has been specified for that property, otherwise the tokenEndpoint will be used instead.
On success, the receivedAccessToken() signal will be emitted. Otherwise, the error property will be set, and the errorChanged() signal will be emitted.
void OAuth2::requestAccessToken(const QString &code = QString(), const QString &state = QString())
Request an access token from the server.
The second step in an ImplicitFlow
, AuthorizationCodeFlow
, or AuthorizationCodeWithPkceFlow
, and the first step in a ClientCredentialsFlow
or ResourceOwnerPassword
flow, is to request an access token from the remote server.
For the former cases, a bearer code (received from the server via a captured redirect from the system web browser) must be provided (and a state value which is similarly received may optionally also be provided and can be checked to protect against some types of attacks).
For the latter two flow types, these parameters are ignored.
On success, the receivedAccessToken() signal will be emitted. Otherwise, the error property will be set, and the errorChanged() signal will be emitted.
void OAuth2::setScope(const QStringList &scopes, const QString &separator = QString::fromLatin1( "," ))
Sets the scope property value to a string generated by joining the given list of scopes with the given separator
Note: Setter function for property scope.
[signal]
void OAuth2::sslErrors(const QList<QSslError> &errors)
This signal is emitted when the helper encounters SSL errors when performing a request.
The application may wish to show the errors to the user, to provide them the opportunity to allow the operation to continue, if they know that the errors are insignificant. In that case, the application can set the ignorableSslErrors property to the given errors and then retry the operation.
See also ignorableSslErrors().