OAuth2 Zig Reference Documentation
OAuth2
Current Version: 11.6.1
Obtain OAuth2 access tokens from desktop and native applications
The Chilkat.OAuth2 class enables desktop and native applications
to perform the OAuth 2.0 Authorization Code Flow for obtaining an initial
access token. The flow begins with StartAuth, which generates
the authorization URL to open in a browser and starts a background listener
for the local redirect callback.
LaunchBrowser to open the generated authorization URL.
AuthFlowState, FailureInfo, and token response data.
After the user grants or denies authorization, Chilkat captures the redirect
response, completes the token exchange, and makes the results available through
properties such as AccessToken, RefreshToken,
AccessTokenResponse, AuthFlowState, and
FailureInfo.
The class also supports PKCE, refresh-token requests, custom authorization and token parameters, secure OS-backed secret resolution, and detailed diagnostic information.
For an extended overview, see OAuth2 Class Overview.
Object Creation
// Add the package once:
// zig fetch --save https://chilkatdownload.com/11.6.1/chilkat-zig-11.6.1.tar.gz
// and in build.zig:
// const chilkat = b.dependency("chilkat", .{ .target = target, .optimize = optimize });
// exe.root_module.addImport("chilkat", chilkat.module("chilkat"));
const chilkat = @import("chilkat");
// Once per process, before any other Chilkat call:
try chilkat.unlockBundle("Anything for 30-day trial");
const o_auth2 = try chilkat.OAuth2.init();
defer o_auth2.deinit();Creates the underlying native Chilkat object. OAuth2 is a one-pointer struct passed by value; copying it copies the handle (two names for one object). Returns error.OutOfMemory if the library could not allocate the object. Use an object from one thread at a time; it may be handed from one thread to another.
Releases the native object. Call it exactly once per object (usually with defer); the handle is invalid afterwards. Objects returned by methods are owned by the caller too and are released the same way.
Wraps a handle obtained from the C API (chilkat.c.CkOAuth2), taking ownership of it. The struct's handle field goes the other way, for anything the Zig API does not cover.
Errors and memory
Methods that can fail return an error union: a method whose only outcome is success or failure returns Error!void; a method producing a string returns (Error || Allocator.Error)![:0]u8; a method producing an object returns Error!T. chilkat.Error is error{ChilkatFailed}; the reason for a failure is in getLastErrorText, and the object remains usable. Properties never fail, and methods that answer a question (hasMember, isUnlocked, ...) return a plain bool.
String arguments are [:0]const u8 (UTF-8; string literals can be passed as is). String results are copies allocated with the allocator argument and owned by the caller, so they stay valid across later calls on the same object.
const text = o_auth2.someMethod(allocator, ...) catch |err| {
const why = try o_auth2.getLastErrorText(allocator);
defer allocator.free(why);
std.debug.print("{s}\n", .{why});
return err;
};
defer allocator.free(text);
Properties
AccessToken
pub fn getAccessToken(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setAccessToken(self: OAuth2, value: [:0]const u8) void
Contains the access_token extracted from the most recent successful token response. It is updated after a successful authorization-code exchange or refresh-token request.
The access token is presented to the protected API, commonly in an HTTP header:
Authorization: Bearer ACCESS_TOKEN
AccessTokenResponse
pub fn getAccessTokenResponse(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Contains the raw response body returned by the token endpoint after a successful authorization-code exchange or refresh-token request.
Most providers return JSON similar to:
{
"token_type": "Bearer",
"expires_in": 3600,
"access_token": "...",
"scope": "read write",
"refresh_token": "..."
}
| Field | Typical meaning |
|---|---|
access_token | Credential presented to the protected API. |
token_type | Usually Bearer. |
expires_in | Access-token lifetime in seconds, when supplied. |
scope | Scopes actually granted, when supplied. |
refresh_token | Credential used to request later access tokens, when issued. |
id_token | OpenID Connect identity token, when requested and issued. |
Some providers return form-encoded text instead of JSON. Use GetAccessTokenResponseSb when a StringBuilder destination is preferred.
AppCallbackUrl
pub fn getAppCallbackUrl(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setAppCallbackUrl(self: OAuth2, value: [:0]const u8) void
Specifies a public HTTPS callback URL on an application-controlled web server when the provider will not redirect directly to localhost or a loopback IP address.
The intermediary endpoint receives the provider's redirect and forwards the complete callback, including code, state, error, and any provider-specific parameters, to the local listener used by Chilkat.
AuthFlowState
pub fn getAuthFlowState(self: OAuth2) i32
Reports the current state of the background authorization flow.
| Value | State | Meaning |
|---|---|---|
0 | Idle | No authorization flow has been started. |
1 | Waiting for redirect | The local listener is waiting for the browser callback. |
2 | Exchanging code | The redirect was received and the background thread is waiting for the token-endpoint response. |
3 | Success | The flow completed and token response properties are available. |
4 | Denied | The authorization server returned an access-denied response. Inspect AccessTokenResponse. |
5 | Failed | The flow failed before successful completion. Inspect FailureInfo and LastErrorText. |
3, 4, or 5. Avoid a tight loop; sleep briefly or use the host environment's timer mechanism.AuthorizationEndpoint
pub fn getAuthorizationEndpoint(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setAuthorizationEndpoint(self: OAuth2, value: [:0]const u8) void
Specifies the authorization endpoint to which the user's browser is directed. StartAuth appends the client identifier, redirect URI, scope, state, PKCE values, and other configured authorization parameters.
| Provider | Authorization endpoint | Token endpoint |
|---|---|---|
https://accounts.google.com/o/oauth2/v2/auth | https://oauth2.googleapis.com/token | |
| Microsoft identity platform | https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize | https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token |
| Salesforce production | https://login.salesforce.com/services/oauth2/authorize | https://login.salesforce.com/services/oauth2/token |
| QuickBooks Online | https://appcenter.intuit.com/connect/oauth2 | https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer |
| X API | https://x.com/i/oauth2/authorize | https://api.x.com/2/oauth2/token |
authorization_endpoint value rather than copying an endpoint from an old example.ClientId
pub fn getClientId(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setClientId(self: OAuth2, value: [:0]const u8) void
Specifies the client identifier assigned when the application is registered with the authorization server. It identifies the application in authorization and token requests.
ClientSecret
pub fn getClientSecret(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setClientSecret(self: OAuth2, value: [:0]const u8) void
Specifies the client secret assigned to a confidential client by the authorization server. It is used when the provider requires the client to authenticate at the token endpoint.
CodeChallenge
pub fn getCodeChallenge(self: OAuth2) bool
pub fn setCodeChallenge(self: OAuth2, value: bool) void
Set to true to enable Proof Key for Code Exchange (PKCE) for the authorization-code flow. The default is false.
When enabled, Chilkat generates a high-entropy code verifier, sends its transformed challenge in the authorization request, and sends the original verifier during the token exchange.
CodeChallengeMethod
pub fn getCodeChallengeMethod(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setCodeChallengeMethod(self: OAuth2, value: [:0]const u8) void
Selects the PKCE transformation used when CodeChallenge is true.
| Value | Behavior |
|---|---|
S256 | Sends a Base64URL-encoded SHA-256 digest of the code verifier. This is the default and recommended method. |
plain | Sends the code verifier itself as the challenge. Use only for compatibility with a provider that cannot support S256. |
S256, do not automatically retry with plain unless the provider is known and explicitly requires it.DebugLogFilePath
pub fn getDebugLogFilePath(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setDebugLogFilePath(self: OAuth2, value: [:0]const u8) void
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
EnableSecrets
pub fn getEnableSecrets(self: OAuth2) bool
pub fn setEnableSecrets(self: OAuth2, value: bool) void
Controls automatic resolution of selected values from operating-system secure storage. The default is false.
When true, the following properties may contain a secret specification beginning with !! instead of a literal value:
The specification has the form:
!![appName|]service[|domain]|username
Chilkat resolves the value through Windows Credential Manager on Windows or Apple Keychain on macOS.
FailureInfo
pub fn getFailureInfo(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Contains diagnostic information when AuthFlowState is 5. The value is cleared when StartAuth begins a new flow.
Use this property for failures in the listener, redirect processing, network connection, or token exchange. Provider-declared authorization denial is represented by state 4 and is normally available in AccessTokenResponse.
IncludeNonce
pub fn getIncludeNonce(self: OAuth2) bool
pub fn setIncludeNonce(self: OAuth2, value: bool) void
Set to true to include an OpenID Connect nonce parameter in the authorization request. The nonce is generated by Chilkat using the byte length specified by NonceLength. The default is false.
In OpenID Connect, the authorization server includes the nonce in the ID token so the client can associate that token with the authorization request and detect replay or token-substitution problems.
nonce protects the relationship between an OpenID Connect request and its ID token. OAuth state correlates the browser callback with the initiating request and is used for CSRF protection. They are related security controls but are not interchangeable.LastErrorHtml
pub fn getLastErrorHtml(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
pub fn getLastErrorText(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
pub fn getLastErrorXml(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
pub fn getLastMethodSuccess(self: OAuth2) bool
pub fn setLastMethodSuccess(self: OAuth2, value: bool) void
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
ListenPort
pub fn getListenPort(self: OAuth2) i32
pub fn setListenPort(self: OAuth2, value: i32) void
Specifies the local TCP port on which Chilkat listens for the browser's OAuth redirect. Choose an available nonprivileged port, typically between 1024 and 65535.
The redirect URI registered with the provider must match the host, selected port, and terminating slash generated by this object. For example:
http://127.0.0.1:3017/
- Use
httpfor a loopback redirect handled entirely on the local computer. - Use
LocalHostto selectlocalhostor127.0.0.1. - Include the final
/when registering the redirect URI.
127.0.0.1 is generally more predictable than resolving localhost.ListenPortRangeEnd
pub fn getListenPortRangeEnd(self: OAuth2) i32
pub fn setListenPortRangeEnd(self: OAuth2, value: i32) void
Defines the inclusive end of a local-listener port range that begins with ListenPort. The default value of 0 disables range selection and uses only ListenPort.
When nonzero, Chilkat selects an available port in the inclusive range. For example, ListenPort=55110 and ListenPortRangeEnd=55117 permit ports 55110 through 55117.
Read ListenPortSelected to determine which port was used.
ListenPortSelected
pub fn getListenPortSelected(self: OAuth2) i32
Returns the local port selected for the current or most recently completed authorization flow.
When a range is configured with ListenPortRangeEnd, use this value to determine the actual loopback redirect port. It is also available for the {listenPort} substitution supported by StateParam.
LocalHost
pub fn getLocalHost(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setLocalHost(self: OAuth2, value: [:0]const u8) void
Selects the host name used in the loopback redirect URI:
| Value | Redirect form |
|---|---|
localhost | http://localhost:{port}/ |
127.0.0.1 | http://127.0.0.1:{port}/ |
The default is localhost. The value must match the redirect URI registered with the provider.
127.0.0.1 avoids DNS and hosts-file ambiguity and is generally preferable when the provider accepts an IPv4 loopback-literal redirect.NonceLength
pub fn getNonceLength(self: OAuth2) i32
pub fn setNonceLength(self: OAuth2, value: i32) void
Specifies the number of random bytes used to generate the hexadecimal OpenID Connect nonce when IncludeNonce is true. The resulting string contains two hexadecimal characters per byte.
The default is 4 bytes, which produces an 8-character hexadecimal nonce.
Oob
pub fn getOob(self: OAuth2) bool
pub fn setOob(self: OAuth2, value: bool) void
Set to true to use the legacy out-of-band redirect URI urn:ietf:wg:oauth:2.0:oob. The application must obtain the displayed authorization code and pass it to ExchangeCodeForToken. The default is false.
RedirectAllowHtml
pub fn getRedirectAllowHtml(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setRedirectAllowHtml(self: OAuth2, value: [:0]const u8) void
Gets or sets the HTML response sent by Chilkat's local listener to the browser after authorization is granted and the redirect is accepted.
The default HTML immediately redirects the browser to Chilkat's confirmation page:
<html>
<head><meta http-equiv='refresh'
content='0;url=https://www.chilkatsoft.com/oauth2_allowed.html'></head>
<body>Thank you for allowing access.</body>
</html>
Replace this value to display application-specific instructions or redirect to a page operated by your organization.
RedirectDenyHtml
pub fn getRedirectDenyHtml(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setRedirectDenyHtml(self: OAuth2, value: [:0]const u8) void
Gets or sets the HTML response sent by Chilkat's local listener to the browser when the authorization server reports that access was denied.
The default HTML immediately redirects the browser to Chilkat's denial page:
<html>
<head><meta http-equiv='refresh'
content='0;url=https://www.chilkatsoft.com/oauth2_denied.html'></head>
<body>The app will not have access.</body>
</html>
Replace this value to display application-specific instructions or redirect to a page operated by your organization.
AuthFlowState value 4. It should normally be handled as a completed flow in which consent was not granted.RedirectReqReceived
pub fn getRedirectReqReceived(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Contains the raw HTTP request received from the browser by Chilkat's local redirect listener. It is intended for troubleshooting callback and provider-parameter problems.
GET /?state=...&code=... HTTP/1.1 Host: 127.0.0.1:3017 User-Agent: ... Accept: text/html,...
The value can include the request target, query or form parameters, and browser-supplied headers.
RefreshToken
pub fn getRefreshToken(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setRefreshToken(self: OAuth2, value: [:0]const u8) void
Gets or sets the refresh token used to obtain new access tokens. Chilkat populates this property when the token endpoint issues a refresh_token, and RefreshAccessToken reads it when creating a refresh request.
A provider may omit the refresh token unless an offline-access scope or provider-specific authorization parameter was requested. A refresh response may also return a replacement token.
Resource
pub fn getResource(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setResource(self: OAuth2, value: [:0]const u8) void
Specifies an optional provider-defined resource parameter identifying the API or audience for which a token is requested.
This is used by some OAuth deployments, including older Microsoft identity endpoints and certain Dynamics configurations. Modern Microsoft v2 endpoints generally identify the target API through scope values instead.
resource value. Do not assume that an API base URL is always the correct value.ResponseMode
pub fn getResponseMode(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setResponseMode(self: OAuth2, value: [:0]const u8) void
Specifies the response mode requested from an OpenID Connect or provider-specific authorization endpoint.
Set to form_post to add response_mode=form_post, causing the authorization server to return parameters in an auto-submitted HTML form that sends an HTTP POST to the redirect URI. The default is an empty string, which omits the parameter and lets the provider choose its normal mode.
ResponseType
pub fn getResponseType(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setResponseType(self: OAuth2, value: [:0]const u8) void
Specifies the authorization response type. The default is code, which requests an authorization code.
Set to id_token+code when a provider requires the OpenID Connect hybrid response response_type=id_token code; the plus sign is the URL-encoded representation of a SPACE in the query string.
Scope
pub fn getScope(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setScope(self: OAuth2, value: [:0]const u8) void
Specifies the access scopes requested from the authorization server. A scope is a provider-defined permission or capability associated with the resulting access token.
OAuth scope values are commonly separated by a single SPACE character:
openid email profile https://www.googleapis.com/auth/drive.readonly
openidrequests OpenID Connect processing and an ID token when used with an appropriate response type.emailandprofilerequest standard OpenID Connect claims.- The Google Drive URI requests read-only access to Drive files.
StateParam
pub fn getStateParam(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setStateParam(self: OAuth2, value: [:0]const u8) void
Allows the application to supply an explicit OAuth state value. Normally this property should remain empty so Chilkat generates a cryptographically random state value and validates the returned value automatically.
The automatically generated state is intentionally not exposed through this property.
The special token {listenPort} may appear in an explicitly supplied value. Chilkat replaces it with the actual listener port selected for the flow.
TokenEndpoint
pub fn getTokenEndpoint(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setTokenEndpoint(self: OAuth2, value: [:0]const u8) void
Specifies the provider's token endpoint. Chilkat sends authorization-code and refresh-token requests to this URL over TLS.
| Provider | Authorization endpoint | Token endpoint |
|---|---|---|
https://accounts.google.com/o/oauth2/v2/auth | https://oauth2.googleapis.com/token | |
| Microsoft identity platform | https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize | https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token |
| Salesforce production | https://login.salesforce.com/services/oauth2/authorize | https://login.salesforce.com/services/oauth2/token |
| QuickBooks Online | https://appcenter.intuit.com/connect/oauth2 | https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer |
| X API | https://x.com/i/oauth2/authorize | https://api.x.com/2/oauth2/token |
TokenType
pub fn getTokenType(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setTokenType(self: OAuth2, value: [:0]const u8) void
Contains the token_type value from the most recent successful token response. The common value is Bearer.
UncommonOptions
pub fn getUncommonOptions(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
pub fn setUncommonOptions(self: OAuth2, value: [:0]const u8) void
Provides a comma-separated list of specialized compatibility options. The default is an empty string and is appropriate for normal OAuth providers.
| Keyword | Effect |
|---|---|
NO_OAUTH2_SCOPE | Omits the scope parameter from the authorization-code token request. |
ExchangeCodeForTokenUsingJson | Sends the authorization-code token request as an HTTP POST with a JSON body instead of the normal form/query representation. |
RefreshTokenUsingJson | Sends the refresh-token request as an HTTP POST with a JSON body. |
UseBasicAuth
pub fn getUseBasicAuth(self: OAuth2) bool
pub fn setUseBasicAuth(self: OAuth2, value: bool) void
Controls how ClientId and ClientSecret are supplied during the authorization-code token exchange.
| Value | Behavior |
|---|---|
true | Sends HTTP Basic authentication using the client ID as the username and the client secret as the password. |
false | Sends the client ID and client secret as request parameters. This is the default. |
invalid_client response.VerboseLogging
pub fn getVerboseLogging(self: OAuth2) bool
pub fn setVerboseLogging(self: OAuth2, value: bool) void
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
pub fn getVersion(self: OAuth2, allocator: Allocator) Allocator.Error![:0]u8
Methods
AddAuthQueryParam
Adds a name/value query parameter to the authorization URL produced by StartAuth. Call the method multiple times to add multiple provider-specific authorization parameters.
Typical examples include provider extensions such as access_type=offline, prompt=consent, or an account-selection hint.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
AddRefreshQueryParam
Adds a provider-specific name/value parameter to requests sent by RefreshAccessToken. Call the method multiple times to add multiple parameters.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
AddTokenQueryParam
Adds a provider-specific name/value parameter to the authorization-code token request that Chilkat sends after receiving the browser redirect. Call the method multiple times to add multiple parameters.
This setting affects the code-for-token exchange performed by StartAuth or ExchangeCodeForToken; it does not alter the browser authorization URL or refresh-token requests.
grant_type, code, or redirect_uri unless instructed by Chilkat support.Returns error.ChilkatFailed on failure; getLastErrorText explains why.
Cancel
Requests cancellation of the authorization flow currently running in the background thread.
Returns true if the cancellation request is accepted. After cancellation, inspect AuthFlowState and FailureInfo to determine the final state.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
ExchangeCodeForToken
Exchanges the authorization code in code for tokens at TokenEndpoint.
This is used when the application obtains the authorization code outside Chilkat's local-listener workflow, most commonly with the legacy out-of-band mode selected by Oob. Configure the same client, endpoint, redirect, PKCE, and token-request settings that the provider requires for the original authorization request.
On success, the token properties and AccessTokenResponse are populated in the same manner as a successful background exchange.
urn:ietf:wg:oauth:2.0:oob. Prefer an authorization-code flow with a loopback redirect and PKCE whenever the provider supports it.Returns error.ChilkatFailed on failure; getLastErrorText explains why.
GetAccessTokenResponseSb
Copies the raw token-endpoint response into sb and returns true on success.
This is the StringBuilder equivalent of reading AccessTokenResponse. The response is commonly JSON, but some providers return form-encoded or other text; this method does not guarantee JSON.
StringBuilder as sensitive data and avoid logging or exposing its contents.Returns error.ChilkatFailed on failure; getLastErrorText explains why.
GetRedirectRequestParam
Returns the decoded value of param_name from the authorization redirect received by Chilkat's local listener.
Call this after the redirect has been received. It is useful for provider-specific parameters in addition to the standard code, state, and error values. For example, QuickBooks can return a company identifier named realmId:
http://localhost:55568/?state=...&code=...&realmId=1234567890
Returns error.ChilkatFailed on failure; getLastErrorText explains why. The string is allocated with allocator and owned by the caller (defer allocator.free(s)).
LaunchBrowser
Asks the operating system to open url in the user's default web browser. On Windows, macOS, and supported Linux desktop environments, an existing browser may open the URL in a new tab.
This method is typically called with the authorization URL returned by StartAuth. Returns false if the operating system cannot launch a browser or open the URL.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
RefreshAccessToken
Sends a refresh-token grant request to TokenEndpoint to obtain a new access token without repeating interactive browser authorization.
Configure ClientId, RefreshToken, and TokenEndpoint, together with whatever client authentication the provider requires. This may include ClientSecret and UseBasicAuth.
On success, Chilkat updates AccessToken, TokenType, and AccessTokenResponse. If the provider rotates refresh tokens and returns a new refresh_token, RefreshToken is also updated.
RefreshToken rather than assuming the previous value remains usable.SetRefreshHeader and AddRefreshQueryParam only when the provider documents additional headers or parameters.Returns error.ChilkatFailed on failure; getLastErrorText explains why.
SetRefreshHeader
Adds or replaces an HTTP request header used by subsequent calls to RefreshAccessToken. name is the header field name and value is its value.
Call this method once for each required header. Passing an empty value removes the named header.
Accept: application/json
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
SleepMs
Suspends the calling thread for millisec milliseconds.
This convenience method is commonly used in a polling loop that checks AuthFlowState while the authorization flow continues on Chilkat's background thread.
StartAuth
Starts an OAuth 2.0 Authorization Code flow and returns the authorization URL that the application should open in the user's browser.
Before calling this method, configure ClientId, AuthorizationEndpoint, TokenEndpoint, the requested Scope, and the redirect-listener settings such as ListenPort. Configure ClientSecret only when the provider requires client authentication for this application type.
- Chilkat constructs and returns the provider's authorization URL.
- Chilkat starts a background thread that listens for the redirect request, validates the returned state, and exchanges the authorization code at the token endpoint.
Open the returned URL with LaunchBrowser or another browser-launch mechanism. Poll AuthFlowState until the flow reaches a terminal state.
CodeChallenge protects the authorization code from interception and is strongly recommended for desktop and other native applications. PKCE does not make a client secret confidential and does not replace client authentication when the provider requires it for a confidential client.LastErrorText before attempting to open the returned URL.Returns error.ChilkatFailed on failure; getLastErrorText explains why. The string is allocated with allocator and owned by the caller (defer allocator.free(s)).
UseConnection
Associates sock with this object for HTTP connections to the token endpoint. This method is optional.
- Pass an unconnected
Socketwhen it is configured with HTTP-proxy, SOCKS-proxy, local-bind, or other connection options that Chilkat should use when opening the token-endpoint connection. - Pass an already connected socket when traffic must travel through an established SSH tunnel or another prebuilt connection.
Without this method, Chilkat opens a direct TLS connection to the token endpoint.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a call, OAuth2 raises three events so your program can show progress and offer a way out. Declare any subset of abortCheck, percentDone and progressInfo in a struct of your own and install a pointer to it with setEventHandler:
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
std.debug.print("{d}%\n", .{pct});
return false; // return true to abort the method in progress
}
pub fn progressInfo(_: *Progress, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var progress = Progress{};
o_auth2.setEventHandler(&progress); // progress must outlive the installation
defer o_auth2.clearEventHandler();
o_auth2.setHeartbeatMs(250); // abortCheck 4 times per second during Chilkat callsInstalls handler, a pointer to any struct, as the receiver of this object's events, replacing any handler installed earlier. The dispatch is resolved at compile time: only the methods the struct declares are called, and a struct declaring none of the three is a compile error. The struct must stay alive, at the same address, until clearEventHandler or deinit.
Removes the handler; events are no longer delivered.
AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from abortCheck or percentDone aborts the running method, which then returns error.ChilkatFailed.
Events fire on the thread that called the method, before that method returns. To abort a long operation from another thread, have abortCheck read a std.atomic.Value(bool), or set the object's AbortCurrent property.
AbortCheck
pub fn abortCheck(self: *T) bool
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
const Abort = struct {
stop: std.atomic.Value(bool) = .init(false),
pub fn abortCheck(self: *Abort) bool {
return self.stop.load(.acquire); // another thread may call abort.stop.store(true, .release)
}
};
var abort = Abort{};
o_auth2.setHeartbeatMs(250); // call abortCheck 4 times per second
o_auth2.setEventHandler(&abort);
defer o_auth2.clearEventHandler();PercentDone
pub fn percentDone(self: *T, pct: i32) bool
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
// pct ranges from 1 to 100.
std.debug.print("Percent done: {d}\n", .{pct});
return false; // return true to abort the method in progress
}
};
var progress = Progress{};
o_auth2.setEventHandler(&progress);
defer o_auth2.clearEventHandler();ProgressInfo
pub fn progressInfo(self: *T, name: [:0]const u8, value: [:0]const u8) void
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
const Info = struct {
pub fn progressInfo(_: *Info, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var info = Info{};
o_auth2.setEventHandler(&info);
defer o_auth2.clearEventHandler();