Chilkat.OAuth2 Class Overview
Chilkat.OAuth2 implements OAuth 2.0 authorization-code workflows
for desktop and native applications. It can generate the browser authorization URL,
listen locally for the redirect callback, exchange the authorization code for
tokens, refresh access tokens, support PKCE, pass custom OAuth parameters, use
secure OS-backed secret resolution, and expose detailed flow state and diagnostic
information.
What the Class Is Used For
Use Chilkat.OAuth2 when an application needs to
authenticate a user with an OAuth2 provider and obtain an access token for API
calls. The class is most commonly used for the authorization code flow where a
browser is launched, the user grants access, and Chilkat receives the redirect on
a local listener such as http://localhost:3017/.
Authorization Code Flow
StartAuth creates the authorization URL and starts
a background listener for the browser redirect.
PKCE Support
Enable CodeChallenge and choose
S256 or plain with
CodeChallengeMethod.
Refresh Tokens
Use RefreshAccessToken to obtain a new access token
from an existing refresh token.
Secure Secret Resolution
Use EnableSecrets so selected properties can resolve
values from Windows Credential Manager or Apple Keychain.
Typical Authorization Code Workflow
-
Create an OAuth2 object.
-
Set ClientId, and set
ClientSecret when required by the provider.
-
Set AuthorizationEndpoint and
TokenEndpoint for the OAuth2 provider.
-
Set Scope to the permissions requested by the
application.
-
Set ListenPort, and optionally
ListenPortRangeEnd when using a port range.
-
Configure optional settings such as CodeChallenge,
UseBasicAuth, LocalHost,
ResponseMode, ResponseType,
Resource, or IncludeNonce.
-
Call StartAuth. Chilkat returns the URL to open in
the browser and starts a background thread to receive the redirect.
-
Call LaunchBrowser with the returned URL, or open it
using another browser-launch mechanism.
-
Monitor AuthFlowState until it becomes success,
denied, or failed.
-
On success, read AccessToken,
RefreshToken,
TokenType, and
AccessTokenResponse.
Core Concepts
| Concept |
Meaning |
Important Members |
| Authorization Endpoint |
Provider URL where the browser is sent so the user can sign in and grant
access.
|
AuthorizationEndpoint |
| Token Endpoint |
Provider URL where the authorization code is exchanged for an access token,
and where refresh-token requests are sent.
|
TokenEndpoint,
RefreshAccessToken
|
| Local Redirect Listener |
Chilkat starts a local background listener to receive the browser redirect
containing the authorization code.
|
ListenPort,
ListenPortRangeEnd,
LocalHost,
StartAuth
|
| PKCE |
Proof Key for Code Exchange. Often used when a client secret is not required
or not appropriate.
|
CodeChallenge,
CodeChallengeMethod
|
| Access Token |
Token used to authenticate API requests after authorization succeeds.
|
AccessToken |
| Refresh Token |
Token used to obtain a new access token after the current access token
expires.
|
RefreshToken,
RefreshAccessToken
|
| Flow State |
Read-only state that indicates whether the OAuth2 flow is idle, waiting,
successful, denied, or failed.
|
AuthFlowState |
Required Setup Properties
| Property |
Purpose |
Guidance |
| ClientId |
Identifies the application registered with the OAuth2 authorization server.
|
Set to the client ID assigned by the provider’s developer portal.
|
| ClientSecret |
Client secret assigned to the application.
|
Required by some providers. May not be required when the provider supports
PKCE for the flow.
|
| AuthorizationEndpoint |
URL used to begin the browser-based authorization request.
|
Set to the provider’s authorization endpoint. Providers may have different
sandbox, tenant, or production endpoints.
|
| TokenEndpoint |
URL used to exchange an authorization code for tokens and to refresh tokens.
|
Set to the provider’s token endpoint.
|
| Scope |
Permissions requested from the user.
|
Scopes are typically separated by spaces, such as
openid email profile.
|
| ListenPort |
Local port used to receive the browser redirect callback.
|
Use a port from 1024 to
65535. Avoid well-known ports such as
80, 443, and
22.
|
Redirect URL format:
If ListenPort is
3017, the provider’s redirect URL should usually be
http://localhost:3017/. The trailing slash is
important.
Localhost Redirect Settings
| Property |
Purpose |
Important Details |
| LocalHost |
Chooses whether the redirect URL uses
localhost or
127.0.0.1.
|
Default is localhost. If set to
127.0.0.1, the redirect URL registered with the
provider should also use 127.0.0.1.
|
| ListenPortRangeEnd |
Allows Chilkat to choose an unused port from a configured range.
|
If non-zero, Chilkat selects an unused port between
ListenPort and
ListenPortRangeEnd. Each possible redirect URL
should be registered with the provider.
|
| ListenPortSelected |
Reports the actual port used for the redirect callback.
|
Read-only. Set when the OAuth2 authorization flow completes.
|
| AppCallbackUrl |
URL on the application’s own web server used as an intermediary redirect.
|
Use only when the OAuth2 provider does not allow localhost or loopback
redirect URLs, or requires HTTPS redirect URLs.
|
| RedirectReqReceived |
Contains the raw HTTP redirect request received from the local browser.
|
Useful for debugging and for inspecting the callback request.
|
HTTP is expected for loopback:
For the local redirect listener, use http://, not
https://. The browser and application are on the same
machine, so the redirect request stays local.
Flow State Values
| AuthFlowState |
Name |
Meaning |
| 0 |
Idle |
No OAuth2 flow has been initiated. |
| 1 |
Awaiting Redirect |
The background thread is waiting for the browser’s redirect HTTP request.
|
| 2 |
Awaiting Final Response |
The background thread is waiting for the final access token response.
|
| 3 |
Success |
The flow completed successfully. Token response data is available in
AccessTokenResponse.
|
| 4 |
Access Denied |
The flow completed, but access was denied. Error response data is available
in AccessTokenResponse.
|
| 5 |
Failed |
The flow failed before completion. Details are available in
FailureInfo.
|
Token Result Properties
| Property / Method |
Purpose |
Guidance |
| AccessToken |
Holds the access token returned by the provider after successful
authorization.
|
Use this token to authenticate API calls.
|
| RefreshToken |
Holds the refresh token returned by the provider, when one is provided.
|
Used by RefreshAccessToken to obtain a new
access token.
|
| TokenType |
Holds the token type from the access token response.
|
Typically bearer.
|
| AccessTokenResponse |
Raw access token response returned by the provider.
|
Often JSON, but not always. Some providers may return plain text parameter
strings.
|
| GetAccessTokenResponseSb |
Copies the access token response into a
StringBuilder.
|
Useful when working with large or mutable response text.
|
| FailureInfo |
Contains failure details when
AuthFlowState = 5.
|
Automatically cleared when a new authorization flow begins with
StartAuth.
|
PKCE, Nonce, State, and Response Options
| Property |
Purpose |
Default / Guidance |
| CodeChallenge |
Enables PKCE.
|
Default is false. Set true when the provider
requires or supports PKCE.
|
| CodeChallengeMethod |
Selects the PKCE code challenge method.
|
Applies only when CodeChallenge is true.
Options are plain and
S256. Default is
S256.
|
| IncludeNonce |
Sends a nonce with the authorization request.
|
Default is false. A nonce is a unique random
value used to help prevent replay attacks.
|
| NonceLength |
Number of random bytes used for the nonce.
|
Default is 4 bytes. The nonce is represented as
hex, so the character length is twice the byte length.
|
| StateParam |
Allows the application to explicitly set the OAuth
state parameter.
|
Usually leave unset so Chilkat generates a random state. The special text
{listenPort} can be included and is replaced by
the actual listen port used.
|
| ResponseMode |
Adds a response_mode parameter to the
authorization request.
|
Set to form_post when required. Default is empty
to omit the parameter.
|
| ResponseType |
Selects the OAuth response type.
|
Default is code. Can be
id_token+code when required.
|
| Resource |
Optional resource query parameter.
|
Used by some providers, such as Microsoft Graph or Microsoft Dynamics CRM
flows.
|
Browser Redirect HTML
| Property |
Shown When |
Purpose |
| RedirectAllowHtml |
The end user grants access.
|
HTML displayed in the browser after the redirect is received and access is
allowed. The default page redirects to a Chilkat “allowed” page, but the
application can replace it with custom HTML.
|
| RedirectDenyHtml |
The end user denies access.
|
HTML displayed in the browser after access is denied. The default page
redirects to a Chilkat “denied” page, but the application can replace it with
custom HTML.
|
Customization tip:
These properties let the application show branded or simpler completion pages
after the local redirect is received.
Custom OAuth Parameters and Headers
| Method |
Affects |
Use Case |
| AddAuthQueryParam |
Authorization URL returned by StartAuth.
|
Add provider-specific query parameters to the browser authorization request.
|
| AddTokenQueryParam |
Internal code-for-token exchange request.
|
Add non-standard parameters required when exchanging the authorization code
for tokens.
|
| AddRefreshQueryParam |
Refresh-token request sent by RefreshAccessToken.
|
Add query parameters to the token refresh request.
|
| SetRefreshHeader |
Refresh-token request headers.
|
Add or remove headers for RefreshAccessToken,
such as Accept: application/json. Set the value
to an empty string to remove a header.
|
| GetRedirectRequestParam |
Local redirect request.
|
Retrieves extra callback parameters provided by a provider, such as
QuickBooks realmId.
|
Refresh Token Workflow
-
Ensure ClientId,
ClientSecret,
RefreshToken, and
TokenEndpoint are set.
-
Optionally add refresh request query parameters with
AddRefreshQueryParam.
-
Optionally add refresh request headers with
SetRefreshHeader.
-
Call RefreshAccessToken.
-
On success, read the updated AccessToken and
RefreshToken properties.
Refresh result:
When RefreshAccessToken succeeds, Chilkat updates both
AccessToken and
RefreshToken with the new values returned by the
provider.
Out-of-Band Flow
| Member |
Purpose |
Guidance |
| Oob |
Uses the legacy out-of-band redirect URI
urn:ietf:wg:oauth:2.0:oob.
|
Default is false. This legacy flow requires the
authorization code to be manually supplied.
|
| ExchangeCodeForToken |
Completes the OOB flow by manually exchanging an authorization code for
tokens.
|
Use specifically for OOB authorization where the code is obtained manually
and passed to this method.
|
Modern guidance:
The OOB flow is described as a legacy flow and has largely been deprecated in favor
of more secure flows such as PKCE.
Secure Secret Resolution
| Property |
Purpose |
Supported Secret-Backed Values |
| EnableSecrets |
Enables automatic resolution of credentials from OS secure storage.
|
Applies to AuthorizationEndpoint,
ClientId,
ClientSecret, and
TokenEndpoint.
|
Secret specification format:
When EnableSecrets is true, supported properties can
use a secret specification beginning with !! in the
form
!![appName|]service[|domain]|username. Chilkat
resolves the value from Windows Credential Manager on Windows or Apple Keychain on
macOS.
Connection and Browser Helpers
| Method |
Purpose |
Important Details |
| LaunchBrowser |
Opens the default browser to the authorization URL.
|
Works on Windows, macOS, and Linux. If a browser is already open, the page is
displayed in a new tab.
|
| UseConnection |
Supplies a Socket for token-endpoint requests.
|
Optional. Use when a proxy, SOCKS proxy, SSH tunnel, or specific socket
options are required. Without this method, the token endpoint connection is a
direct TLS connection.
|
| Cancel |
Stops an ongoing OAuth2 authorization flow.
|
Use to cancel a pending flow that is waiting for redirect or final response.
|
| SleepMs |
Convenience method to sleep the calling thread.
|
Often used while polling AuthFlowState.
|
| LoadTaskCaller |
Loads the caller of an async method’s task.
|
Used in asynchronous task workflows.
|
Token Request Authentication and Uncommon Options
| Member |
Purpose |
Behavior |
| UseBasicAuth |
Controls how client_id and
client_secret are sent during code-for-token
exchange.
|
If true, they are sent in an
Authorization: Basic ... header. If false, they
are sent as query parameters.
|
| UncommonOptions |
Comma-separated keywords for uncommon provider requirements.
|
Normally empty. Use only when a documented option is needed.
|
| Uncommon Option |
Behavior |
| NO_OAUTH2_SCOPE |
Do not include the scope parameter when
exchanging the authorization code for an access token.
|
| ExchangeCodeForTokenUsingJson |
Uses an HTTP POST with a JSON request body for the final code-for-token
request.
|
| RefreshTokenUsingJson |
Uses an HTTP POST with a JSON request body for the token refresh request.
|
Provider Endpoint Examples
| Provider |
Authorization Endpoint |
Token Endpoint |
| Google |
https://accounts.google.com/o/oauth2/v2/auth |
https://www.googleapis.com/oauth2/v4/token |
| Microsoft |
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize |
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token |
| X.com |
https://x.com/i/oauth2/authorize |
https://api.x.com/2/oauth2/token |
| Salesforce |
https://login.salesforce.com/services/oauth2/authorize |
https://login.salesforce.com/services/oauth2/token |
| QuickBooks |
https://appcenter.intuit.com/connect/oauth2 |
https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer |
Endpoint note:
OAuth2 providers may have tenant-specific, sandbox, or production endpoints.
Always use the endpoints required for the registered application and target
environment.
Method Summary by Category
| Category |
Methods / Properties |
Purpose |
| Start authorization |
StartAuth,
LaunchBrowser,
Cancel
|
Begin the OAuth2 flow, open the browser, or cancel a pending flow.
|
| Flow state and diagnostics |
AuthFlowState,
FailureInfo,
RedirectReqReceived,
LastErrorText
|
Monitor progress and diagnose redirect, token exchange, denial, or failure
conditions.
|
| Token results |
AccessToken,
RefreshToken,
TokenType,
AccessTokenResponse,
GetAccessTokenResponseSb
|
Retrieve token data after successful authorization.
|
| Refresh token |
RefreshAccessToken,
AddRefreshQueryParam,
SetRefreshHeader
|
Obtain a new access token using an existing refresh token.
|
| Custom parameters |
AddAuthQueryParam,
AddTokenQueryParam,
AddRefreshQueryParam,
GetRedirectRequestParam
|
Add non-standard provider parameters or retrieve additional redirect
parameters.
|
| OOB flow |
Oob,
ExchangeCodeForToken
|
Support the legacy manual authorization-code flow.
|
| Connection customization |
UseConnection |
Use a socket configured for proxy, SOCKS, SSH tunnel, or custom socket
options for token endpoint requests.
|
| Async and utility |
LoadTaskCaller,
SleepMs
|
Support async task workflows and polling loops.
|
Diagnostics and Troubleshooting
| Problem Area |
Member |
What to Check |
| Browser redirect is never received |
ListenPort,
LocalHost,
RedirectReqReceived
|
Confirm the registered redirect URL exactly matches the local host and port,
including the trailing slash.
|
| Provider requires a port range |
ListenPortRangeEnd,
ListenPortSelected
|
Register each possible redirect URL and read
ListenPortSelected after completion.
|
| Flow stops before token response |
AuthFlowState,
FailureInfo
|
If AuthFlowState = 5, inspect
FailureInfo.
|
| User denied consent |
AuthFlowState,
AccessTokenResponse
|
If AuthFlowState = 4, inspect the error
response in AccessTokenResponse.
|
| Token response is not JSON |
AccessTokenResponse |
Do not assume every provider returns JSON. Some responses may be plain text
URL-encoded parameter strings.
|
| Refresh token request fails |
ClientId,
ClientSecret,
RefreshToken,
TokenEndpoint
|
Confirm all required properties are set and add provider-specific refresh
query parameters or headers when needed.
|
| Provider requires client credentials in Basic auth |
UseBasicAuth |
Set UseBasicAuth = true so the token exchange
sends credentials in the Authorization: Basic
header.
|
| Need operation details after failure |
LastErrorText |
Check diagnostic text after failed or unexpected authorization, token
exchange, refresh, browser launch, custom-parameter, or socket operations.
|
Common Pitfalls
| Pitfall |
Better Approach |
| Omitting the trailing slash from the registered redirect URL. |
Register the redirect as http://localhost:3017/
or http://127.0.0.1:3017/, including the final
slash.
|
| Using localhost in the app registration while LocalHost is set to 127.0.0.1. |
Keep LocalHost and the provider’s registered
redirect URL consistent.
|
| Assuming the generated random state can be read from StateParam. |
StateParam is for explicitly setting state.
Chilkat’s generated random state is not reflected in this property.
|
| Assuming ClientSecret is always required. |
Some PKCE flows may not require a client secret. Follow the provider’s
requirements.
|
| Using the OOB flow for new integrations. |
Prefer the normal redirect flow with PKCE when supported. OOB is described
as a legacy flow.
|
| Expecting every provider to return a refresh token. |
Refresh tokens are provider- and scope-dependent. For example, some providers
require an offline-access scope.
|
| Hard-coding secrets directly in source code. |
Use EnableSecrets and secret specification
strings when Windows Credential Manager or Apple Keychain should provide the
values.
|
Best Practices
| Recommendation |
Reason |
| Use PKCE when the provider supports or requires it. |
PKCE improves security for native and desktop OAuth2 flows and can eliminate
the need for a client secret in some cases.
|
| Use a high, non-reserved listen port. |
Ports in the 1024 to
65535 range avoid conflicts with system
services.
|
| Keep redirect URL registration exact. |
Provider redirect matching is often strict; host, port, and trailing slash
must match.
|
| Use AuthFlowState instead of guessing progress. |
It gives a clear indication of waiting, success, denial, or failure.
|
| Inspect the full AccessTokenResponse. |
Providers can return additional fields such as scope, expiry, token type, and
refresh token.
|
| Add provider-specific parameters with the dedicated methods. |
AddAuthQueryParam,
AddTokenQueryParam, and
AddRefreshQueryParam keep custom requirements
organized by request stage.
|
| Use UseConnection only when special transport behavior is needed. |
Direct TLS is used by default. A custom socket is only needed for proxy,
SOCKS, SSH tunnel, or custom socket options.
|
| Check LastErrorText, FailureInfo, and RedirectReqReceived when troubleshooting. |
Together, these provide diagnostics for setup problems, callback problems,
token exchange failures, and provider-specific errors.
|
Summary
Chilkat.OAuth2 is the Chilkat class for performing
OAuth2 authorization flows in desktop and native applications. It can create the
authorization URL, launch the browser, listen locally for the redirect, exchange
authorization codes for tokens, refresh access tokens, support PKCE, add custom
provider parameters, use secure OS-backed secret lookup, and expose detailed state
and diagnostic information.
The most important practical guidance is to configure the provider endpoints,
client ID, scope, and exact redirect URL carefully; use PKCE when appropriate; set
the listen host and port to match the provider registration; monitor
AuthFlowState; inspect the full token response; and use
LastErrorText, FailureInfo,
and RedirectReqReceived for troubleshooting.