Let your users authorize with external OAuth 2.0 providers. More...
| Import Statement: | import Felgo 4.0 |
| Since: | Felgo 4.2.0 |
| Inherits: |
(since Felgo 4.4.0)(since Felgo 4.4.0)The OAuth 2.0 Plugin lets your users authorize with external OAuth 2.0 providers.
OAuth 2.0 is the industry-standard protocol for authorization. Read more at https://oauth.net/2/.
This item lets your users authorize with an OAuth 2.0-enabled API.
Any app that persists an OAuth session across launches needs to handle three startup paths. Use the following three handlers to cover all cases:
OAuth2Client { // Path 1: no session — user never logged in, or last logout was clean. onSessionNotFound: { showLoginScreen() } // Path 2: session restored — token was valid or a startup refresh succeeded. // Safe to make authenticated API calls from here. onAccessTokenReady: { restoreSession() } // Path 3: session existed but startup token refresh failed (e.g. refresh token expired). // isAuthenticated drops to false after having been true during the refresh attempt. onIsAuthenticatedChanged: { if (!isAuthenticated) showLoginScreen() } }
Note: Path 3 is easy to overlook: when a startup token refresh is triggered, isAuthenticated is true when pluginLoaded fires (the session is still considered valid while refreshing), so onSessionNotFound never triggers. If the refresh then fails, only onIsAuthenticatedChanged
reflects this.
Note: Do not check isAuthenticated inside onPluginLoadedChanged to detect a missing session. Due to QML binding evaluation ordering, authStatus may briefly read as Initializing at that moment even though the plugin is fully loaded. onSessionNotFound is the reliable signal for this
case — it is emitted from code after all startup state has settled.
See OAuth 2.0 Plugin — Example Usage for a full example.
|
accessToken : string |
Read-only property containing the currently active access token.
It contains a non-empty value whenever isAuthenticated is true.
Note: When authStatus is OAuth2Client.RefreshingTokens, this property may still hold an expired token. For API calls, use getValidAccessToken() instead, which automatically refreshes the token if necessary before returning it.
For more information about access tokens, see https://oauth.net/2/access-tokens/.
See also getValidAccessToken(), refreshToken, accessTokenExpirationDate, tokensRefreshed, and accessTokenReady.
|
accessTokenExpirationDate : date |
Read-only property containing the accessToken's expiration date.
See also accessToken.
|
authStatus : int |
Read-only property containing current authentication status.
It can contain one of the following values:
OAuth2Client.Initializing: The plugin is not yet loaded. isAuthenticated is false in this state.
OAuth2Client.NotAuthenticated: The plugin is loaded but no credentials are available.OAuth2Client.Granted: A valid accessToken is available. Only in this case, isAuthenticated contains true.
OAuth2Client.RefreshingTokens: The item is currently requesting new credentials via the refreshToken.
See also isAuthenticated and pluginLoaded.
|
authTimeout : int |
Timeout in seconds for the entire authentication flow.
When authenticate() is called, a timer starts. If authentication does not complete (success or failure) within this many seconds, the flow is treated as an error and authenticationError() is emitted with the message "Authentication timed out.".
Set to 0 to disable the timeout.
The default value is 300 (5 minutes).
See also authenticate() and authenticationError().
|
authUrl : url |
Set this property to the authorization endpoint URL.
A call to authenticate() opens this URL in a system browser. It adds the relevant parameters as specified by OAuth 2.0 automatically. Use the properties of this type to configure them.
This property is always required.
See also pkceType, promptType, scopes, tokenUrl, and authenticate().
|
callbackUrl : url |
Set this property to your app's callback URL.
The flow uses this URL to return to the app after the user authenticated themselves.
Use any custom URL scheme with this property. On Android, register your app to open via this URL scheme in AndroidManifest.xml. See Android Integration Steps for details.
This property is required on iOS, Android, and macOS.
On Windows and Linux this property has no effect. See desktopCallbackPort and effectiveCallbackUrl for details.
See also desktopCallbackPort and effectiveCallbackUrl.
|
clientId : string |
Your apps client ID.
You usually obtain this ID from the backend. It identifies your application with the API.
This property is always required.
See also clientSecret.
|
clientIdentifier : string |
A unique identifier for this OAuth2Client instance.
You can use this property if you have multiple different OAuth2Clients in your application. The item persists its internal state via this identifier.
You can also omit setting this property. The item then uses a hash of the authUrl and clientId as a default value.
|
clientSecret : string |
Your apps client secret.
You usually obtain this secret from the backend. It authenticates your application with the API.
This property is not always required. It is added to the token endpoint call only when it is set.
See also clientId.
|
desktopCallbackPort : int |
Sets the preferred local port for the OAuth callback server used on Windows and Linux.
On those platforms the plugin starts a temporary HTTP server on 127.0.0.1 to receive the OAuth callback from the system browser.
Set this to a specific port number if your OAuth provider requires an exact redirect URI, e.g. http://127.0.0.1:8085/callback. Register that same URI in your provider's dashboard.
The default value is 0, which lets the OS pick any available port. This is the recommended approach for providers that follow RFC 8252 §7.3 (e.g. Google, GitHub), which accept 127.0.0.1 on any port.
Note: This property has no effect on iOS, macOS, and Android, which use a custom URL scheme via callbackUrl instead.
This property was introduced in Felgo 4.4.0.
See also callbackUrl and effectiveCallbackUrl.
|
effectiveCallbackUrl : url |
Read-only property containing the redirect URI that was actually used in the last authentication flow.
"http://127.0.0.1:<port>/callback", where <port> is determined by desktopCallbackPort or the OS.
This value is what the plugin sends as redirect_uri to both the authorization endpoint and the token endpoint. Use it to verify the URI configured in your provider's dashboard matches what the
plugin uses.
This property was introduced in Felgo 4.4.0.
See also callbackUrl and desktopCallbackPort.
|
grantedScopes : var |
Read-only property containing the scopes granted by the backend.
This is usually the same or a subset of the requested scopes.
See also scopes and authenticate().
|
httpAuthenticationHeader : string |
Optionally sets the authentication header for the token retrieval.
Some APIs require HTTP authentication.
The default value of this property is an empty string. In this case, it uses no authentication header.
See also scopeDelimiter, pkceType, promptType, and authenticate().
|
httpContentType : string |
Optionally sets the content type for the token retrieval POST request.
The token endpoint may accept different content types.
This item supports the following types:
"application/json": The default value of this property. Sends data in JSON format."application/x-www-form-urlencoded: Sends data in URL-encoded format.See also tokenUrl and authenticate().
|
idToken : string |
Read-only property containing the OpenID Connect ID token.
It contains a value if the field id_token was set in the token response.
For more information about ID tokens, see https://openid.net/specs/openid-connect-core-1_0.html#IDToken.
See also accessToken and idTokenData.
|
idTokenData : var |
Read-only property containing the OpenID Connect ID token payload.
It contains the idToken's payload, parsed as a JSON object.
Note: This property only contains a value if the idToken was validated and decoded successfully. It supports the validation algorithms "SH256" (SHA-256) and "none" (no validation).
See also accessToken and idToken.
|
isAuthenticated : bool |
Read-only property containing true when the user is successfully authenticated.
This is true when authStatus is OAuth2Client.Granted or OAuth2Client.RefreshingTokens. It remains true while a token refresh is in progress, since the user's session is still valid. It only becomes false if no
valid session exists, a refresh fails, or the user logs out.
Note: While authStatus is OAuth2Client.RefreshingTokens, the accessToken
may be expired. Use getValidAccessToken() or listen to tokensRefreshed before making API
calls.
Note: isAuthenticated is always false while authStatus is OAuth2Client.Initializing (i.e. before
pluginLoaded becomes true). Do not rely on it until after pluginLoaded is
true.
See also authStatus, pluginLoaded, and tokensRefreshed.
|
pkceLength : int |
|
pkceType : int |
Sets the desired PKCE method to use during authorization.
Set it to one of the following values:
OAuth2Client.None: The default value of this property. No PKCE challenge is used during authorization.OAuth2Client.Plain: A plain PKCE challenge is used during authorization.OAuth2Client.SHA256: A SHA-256 hash of the PKCE challenge is used during authorization.Note: Not all backends may support all PKCE types.
Read more about this functionality in the section PKCE Extension.
See also pkceLength, promptType, scopes, and authenticate().
|
pluginLoaded : bool |
Read-only property that is true once the plugin has finished loading and is ready to use.
It starts as false and becomes true after the plugin initializes. While it is false, authStatus returns OAuth2Client.Initializing and isAuthenticated returns false.
See also authStatus and isAuthenticated.
|
promptType : int |
Optionally sets which user prompt to display during authentication.
Set it to one of the following values:
OAuth2Client.NotSet: The default value of this property. Requests no specific prompt type.OAuth2Client.None: Does request no user prompt. If already authenticated, the login may happen without user input.OAuth2Client.Consent: Re-requests the user's consent to authorize, if already given.OAuth2Client.Login: Re-requests the user to login, if already logged in.OAuth2Client.SelectAccount: Requests the user to re-select an account.OAuth2Client.Create: Requests the user to create a new account.Note: Not all backends may support all prompt types.
See also pkceType, scopes, and authenticate().
|
refreshToken : string |
Read-only property containing the currently active refresh token.
A refresh token is generally longer-lived than an access token. The item uses it to request a new access token.
This property is only set if the token endpoint returns a refresh token in its response.
It is usually not necessary to use this token directly. You can call requestRefreshedTokens() to request a new access token via the refresh token.
For more information about refresh tokens, see https://oauth.net/2/grant-types/refresh-token/.
See also accessToken, refreshTokenExpirationDate, and requestRefreshedTokens().
|
refreshTokenExpirationDate : date |
Read-only property containing the refreshToken's expiration date.
See also refreshToken and requestRefreshedTokens().
|
refreshTokensAutomatically : bool |
If set to true, the item will automatically request refreshed tokens, if the current access token is expired.
Note: It only checks the accessTokenExpirationDate on startup, after the plugin is loaded. You can also request a refreshed token with a manual call to requestRefreshedTokens(), independent of this property's value.
The default value of this property is true.
See also accessToken, refreshToken, and requestRefreshedTokens().
|
scopeDelimiter : string |
|
scopes : var |
Optionally sets the authorization scopes to request.
Set it to an array of strings, eg. scopes: ["users.read", "tweet.read"]
Note: The item sends the scopes as parameter via the authUrl. It joins them via the scopeDelimiter.
See also scopeDelimiter, pkceType, promptType, and authenticate().
|
tokenUrl : url |
Set this property to the token endpoint URL.
After the user authorization via the authUrl is done, an access token is obtained via a REST call to this endpoint.
This property is always required.
See also authUrl, accessToken, and authenticate().
|
accessTokenExpired() |
The item emits this signal when the accessToken expires during an active session.
Subscribe to this signal to react to mid-session expiry. If refreshTokensAutomatically is true, the item automatically
calls requestRefreshedTokens() and emits tokensRefreshed on success. Otherwise, call requestRefreshedTokens() or authenticate() manually.
Note: The item also checks token expiry at startup. This signal only fires for expirations that occur after the plugin has loaded.
Note: The corresponding handler is onAccessTokenExpired.
See also accessToken, accessTokenExpirationDate, refreshTokensAutomatically, and requestRefreshedTokens().
|
accessTokenReady() |
The item emits this signal once at startup when the accessToken is confirmed valid and safe to use.
It fires after pluginLoaded becomes true, in two cases:
This signal does not fire for runtime refreshes triggered by requestRefreshedTokens() or refreshTokensAutomatically — use tokensRefreshed for those. It also does not fire if the user is not authenticated or if a startup refresh fails.
Use this as a single, unambiguous "safe to make API calls" entry point for app startup. See Handling Startup Authentication for the canonical three-handler pattern.
Note: The corresponding handler is onAccessTokenReady.
See also pluginLoaded, tokensRefreshed, isAuthenticated, and sessionNotFound.
|
authenticationError(string message) |
The item emits this signal when there is an error during the authentication flow.
The parameter message contains information about the error.
Note: The corresponding handler is onAuthenticationError.
See also authenticate().
|
sessionNotFound() |
The item emits this signal once at startup when the plugin is loaded and no prior OAuth session exists — the user has never logged in, or the last logout was clean.
It fires after pluginLoaded becomes true, when there is no stored accessToken and
no startup token refresh is in progress.
Use this as the reliable entry point for showing a login screen at startup. It is emitted from code after all startup state has settled, so isAuthenticated and authStatus are guaranteed to reflect their correct values when this signal fires.
Note: This signal does not fire if a startup token refresh is in progress. If the refresh then fails, onIsAuthenticatedChanged fires instead.
See Handling Startup Authentication for the canonical three-handler pattern.
Note: The corresponding handler is onSessionNotFound.
See also pluginLoaded, accessTokenReady, and isAuthenticated.
|
tokensRefreshed() |
The item emits this signal when a token refresh completes successfully.
Use this to trigger actions that depend on fresh tokens, such as retrying a queued API call, without conflating it with a fresh authenticate() flow.
Note: The corresponding handler is onTokensRefreshed.
See also requestRefreshedTokens() and isAuthenticated.
|
authenticate() |
Starts the authentication flow.
If the authentication is successful, isAuthenticated will contain true and accessToken will contain a valid token.
Otherwise, it emits the authenticationError() signal.
See also accessToken, isAuthenticated, and authenticationError().
|
getValidAccessToken(callback) |
Obtains a non-expired access token and passes it to the callback function.
Unlike reading accessToken directly, this method checks whether the current token has expired and automatically refreshes it if necessary before invoking the callback.
Use this method before making authenticated API calls to avoid sending expired tokens.
Note: This method checks the local accessTokenExpirationDate. A token that has not expired locally can still be rejected by the server (e.g. if it was revoked).
The callback receives a single string argument:
"" if the token could not be obtained (e.g. no refresh token available, or the refresh request failed).If a token refresh is already in progress, the callback is queued and invoked once the refresh completes. Multiple concurrent callers are handled correctly.
See also accessToken, requestRefreshedTokens(), and tokensRefreshed.
|
logout() |
Logs out the current user.
This deletes the current accessToken and refreshToken. It sets authStatus to OAuth2Client.NotAuthenticated.
Note: It is possible that a subsequent call to authenticate() logs the same user in again automatically. You can use the promptType property to request manual login or consent again.
See also promptType and authenticate().
|
requestRefreshedTokens() |
Requests refreshed tokens from the token endpoint.
This method only has an effect if refreshToken contains a valid value.
Read more about this functionality in the section Token Refresh.
See also accessToken, refreshToken, and refreshTokensAutomatically.