Class OAuth2
- All Implemented Interfaces:
AutoCloseable
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.
Browser-based authorization
Use LaunchBrowser to open the generated authorization URL.
Local redirect handling Chilkat listens locally for the provider’s redirect response.
Token exchange The authorization code is exchanged for access and refresh tokens.
Diagnostics and state
Inspect 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.
Note: This class is primarily used to obtain the initial OAuth2 access token. After that, applications typically use the refresh token to obtain new access tokens for an extended period without requiring further user interaction.
For an extended overview, see OAuth2 Class Overview.
Event-capable: long-running methods report progress through a ProgressListener installed
with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier),
onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddAuthQueryParam(String name, String value)Adds a name/value query parameter to the authorization URL produced by.startAuth()voidaddRefreshQueryParam(String name, String value)Adds a provider-specific name/value parameter to requests sent by.refreshAccessToken()voidaddTokenQueryParam(String name, String value)Adds a provider-specific name/value parameter to the authorization-code token request that Chilkat sends after receiving the browser redirect.voidcancel()Requests cancellation of the authorization flow currently running in the background thread.voidexchangeCodeForToken(String code)Exchanges the authorization code incodefor tokens at.getTokenEndpoint()Contains theaccess_tokenextracted from the most recent successful token response.Contains the raw response body returned by the token endpoint after a successful authorization-code exchange or refresh-token request.voidCopies the raw token-endpoint response intosband returnstrueon success.Specifies a public HTTPS callback URL on an application-controlled web server when the provider will not redirect directly tolocalhostor a loopback IP address.intReports the current state of the background authorization flow.Specifies the authorization endpoint to which the user's browser is directed.Specifies the client identifier assigned when the application is registered with the authorization server.Specifies the client secret assigned to a confidential client by the authorization server.booleanSet totrueto enable Proof Key for Code Exchange (PKCE) for the authorization-code flow.Selects the PKCE transformation used whenisgetCodeChallenge()true.booleanControls automatic resolution of selected values from operating-system secure storage.Contains diagnostic information whenisgetAuthFlowState()5.booleanSet totrueto include an OpenID Connectnonceparameter in the authorization request.intSpecifies the local TCP port on which Chilkat listens for the browser's OAuth redirect.intDefines the inclusive end of a local-listener port range that begins with.getListenPort()intReturns the local port selected for the current or most recently completed authorization flow.Selects the host name used in the loopback redirect URI:intSpecifies the number of random bytes used to generate the hexadecimal OpenID Connect nonce whenisgetIncludeNonce()true.booleangetOob()Set totrueto use the legacy out-of-band redirect URIurn:ietf:wg:oauth:2.0:oob.Returns the installed listener, ornull.Gets or sets the HTML response sent by Chilkat's local listener to the browser after authorization is granted and the redirect is accepted.Gets or sets the HTML response sent by Chilkat's local listener to the browser when the authorization server reports that access was denied.Contains the raw HTTP request received from the browser by Chilkat's local redirect listener.getRedirectRequestParam(String paramName)Returns the decoded value ofparamNamefrom the authorization redirect received by Chilkat's local listener.Gets or sets the refresh token used to obtain new access tokens.Specifies an optional provider-definedresourceparameter identifying the API or audience for which a token is requested.Specifies the response mode requested from an OpenID Connect or provider-specific authorization endpoint.Specifies the authorization response type.getScope()Specifies the access scopes requested from the authorization server.Allows the application to supply an explicit OAuthstatevalue.Specifies the provider's token endpoint.Contains thetoken_typevalue from the most recent successful token response.Provides a comma-separated list of specialized compatibility options.booleanControls howClientIdandClientSecretare supplied during the authorization-code token exchange.voidlaunchBrowser(String url)Asks the operating system to openurlin the user's default web browser.voidonAbortCheck(BooleanSupplier callback)Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it.voidonPercentDone(IntPredicate callback)Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it.voidonProgressInfo(BiConsumer<String,String> callback)Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds.voidSends a refresh-token grant request toto obtain a new access token without repeating interactive browser authorization.getTokenEndpoint()voidsetAccessToken(String value)Sets theAccessTokenproperty; seegetAccessToken().voidsetAppCallbackUrl(String value)Sets theAppCallbackUrlproperty; seegetAppCallbackUrl().voidsetAuthorizationEndpoint(String value)Sets theAuthorizationEndpointproperty; seegetAuthorizationEndpoint().voidsetClientId(String value)Sets theClientIdproperty; seegetClientId().voidsetClientSecret(String value)Sets theClientSecretproperty; seegetClientSecret().voidsetCodeChallenge(boolean value)Sets theCodeChallengeproperty; seegetCodeChallenge().voidsetCodeChallengeMethod(String value)Sets theCodeChallengeMethodproperty; seegetCodeChallengeMethod().voidsetEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().voidsetIncludeNonce(boolean value)Sets theIncludeNonceproperty; seegetIncludeNonce().voidsetListenPort(int value)Sets theListenPortproperty; seegetListenPort().voidsetListenPortRangeEnd(int value)Sets theListenPortRangeEndproperty; seegetListenPortRangeEnd().voidsetLocalHost(String value)Sets theLocalHostproperty; seegetLocalHost().voidsetNonceLength(int value)Sets theNonceLengthproperty; seegetNonceLength().voidsetOob(boolean value)Sets theOobproperty; seegetOob().voidsetProgressListener(ProgressListener listener)Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.voidsetRedirectAllowHtml(String value)Sets theRedirectAllowHtmlproperty; seegetRedirectAllowHtml().voidsetRedirectDenyHtml(String value)Sets theRedirectDenyHtmlproperty; seegetRedirectDenyHtml().voidsetRefreshHeader(String name, String value)Adds or replaces an HTTP request header used by subsequent calls to.refreshAccessToken()voidsetRefreshToken(String value)Sets theRefreshTokenproperty; seegetRefreshToken().voidsetResource(String value)Sets theResourceproperty; seegetResource().voidsetResponseMode(String value)Sets theResponseModeproperty; seegetResponseMode().voidsetResponseType(String value)Sets theResponseTypeproperty; seegetResponseType().voidSets theScopeproperty; seegetScope().voidsetStateParam(String value)Sets theStateParamproperty; seegetStateParam().voidsetTokenEndpoint(String value)Sets theTokenEndpointproperty; seegetTokenEndpoint().voidsetTokenType(String value)Sets theTokenTypeproperty; seegetTokenType().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidsetUseBasicAuth(boolean value)Sets theUseBasicAuthproperty; seegetUseBasicAuth().voidsleepMs(int millisec)Suspends the calling thread formillisecmilliseconds.Starts an OAuth 2.0 Authorization Code flow and returns the authorization URL that the application should open in the user's browser.voiduseConnection(Socket sock)Associatessockwith this object for HTTP connections to the token endpoint.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
OAuth2
public OAuth2()Creates a newOAuth2object.
-
-
Method Details
-
getAccessToken
Contains theaccess_tokenextracted 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
Bearer credential: Anyone possessing a bearer access token can use the authority it grants until the token expires or is revoked. Store it securely, transmit it only over TLS, and never place it in a URL or ordinary log.
- Returns:
- the value of the
AccessTokenproperty
-
setAccessToken
Sets theAccessTokenproperty; seegetAccessToken().- Parameters:
value- the new value (notnull)
-
getAccessTokenResponse
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_tokenCredential presented to the protected API.token_typeUsuallyBearer.expires_inAccess-token lifetime in seconds, when supplied.scopeScopes actually granted, when supplied.refresh_tokenCredential used to request later access tokens, when issued.id_tokenOpenID Connect identity token, when requested and issued.Some providers return form-encoded text instead of JSON. Use
when agetAccessTokenResponseSb(StringBuilder)StringBuilderdestination is preferred.Sensitive response: This property can contain live credentials. Do not include it in ordinary logs, exception reports, telemetry, or user-visible diagnostics.
- Returns:
- the value of the
AccessTokenResponseproperty (read-only)
-
getAppCallbackUrl
Specifies a public HTTPS callback URL on an application-controlled web server when the provider will not redirect directly tolocalhostor 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.Security responsibility: The intermediary handles a short-lived authorization code and state value. It must use HTTPS, avoid logging sensitive query data, validate and preserve parameters correctly, and prevent use as an open redirect. Use only when necessary: A direct loopback redirect with PKCE is simpler and avoids introducing a public relay. Prefer it whenever the provider supports native-application loopback redirects.
- Returns:
- the value of the
AppCallbackUrlproperty
-
setAppCallbackUrl
Sets theAppCallbackUrlproperty; seegetAppCallbackUrl().- Parameters:
value- the new value (notnull)
-
getAuthFlowState
public int getAuthFlowState()Reports the current state of the background authorization flow.Value State Meaning
0Idle No authorization flow has been started.1Waiting for redirect The local listener is waiting for the browser callback.2Exchanging code The redirect was received and the background thread is waiting for the token-endpoint response.3Success The flow completed and token response properties are available.4Denied The authorization server returned an access-denied response. Inspect.getAccessTokenResponse()5Failed The flow failed before successful completion. InspectandgetFailureInfo()LastErrorText.Polling pattern: After opening the authorization URL, periodically read this property until it is
3,4, or5. Avoid a tight loop; sleep briefly or use the host environment's timer mechanism.- Returns:
- the value of the
AuthFlowStateproperty (read-only)
-
getAuthorizationEndpoint
Specifies the authorization endpoint to which the user's browser is directed.appends the client identifier, redirect URI, scope, state, PKCE values, and other configured authorization parameters.startAuth()Provider Authorization endpoint Token endpoint
Google
https://accounts.google.com/o/oauth2/v2/authhttps://oauth2.googleapis.com/tokenMicrosoft identity platform
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorizehttps://login.microsoftonline.com/{tenant}/oauth2/v2.0/tokenSalesforce production
https://login.salesforce.com/services/oauth2/authorizehttps://login.salesforce.com/services/oauth2/tokenQuickBooks Online
https://appcenter.intuit.com/connect/oauth2https://oauth.platform.intuit.com/oauth2/v1/tokens/bearerX API
https://x.com/i/oauth2/authorizehttps://api.x.com/2/oauth2/tokenPrefer provider metadata: When the provider publishes OAuth authorization-server metadata or OpenID Connect discovery metadata, use its current
authorization_endpointvalue rather than copying an endpoint from an old example. Environment and tenant matter: Sandbox, production, regional, and tenant-specific deployments can use different endpoints. The authorization and token endpoints must belong to the same provider environment.- Returns:
- the value of the
AuthorizationEndpointproperty
-
setAuthorizationEndpoint
Sets theAuthorizationEndpointproperty; seegetAuthorizationEndpoint().- Parameters:
value- the new value (notnull)
-
getClientId
Specifies the client identifier assigned when the application is registered with the authorization server. It identifies the application in authorization and token requests.Not a password: A client ID is normally public and may appear in authorization URLs. Its security role is identification, not authentication.
- Returns:
- the value of the
ClientIdproperty
-
setClientId
Sets theClientIdproperty; seegetClientId().- Parameters:
value- the new value (notnull)
-
getClientSecret
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.Protect this value: A client secret is a credential. Do not place it in source control, logs, browser URLs, or distributable desktop/mobile binaries. Native applications are public clients and generally cannot keep a shared secret confidential; use PKCE and follow the provider's registration requirements. PKCE is separate: PKCE protects the authorization code. It does not transform an embedded secret into a confidential credential and does not replace client authentication for a provider that requires it.
- Returns:
- the value of the
ClientSecretproperty
-
setClientSecret
Sets theClientSecretproperty; seegetClientSecret().- Parameters:
value- the new value (notnull)
-
getCodeChallenge
public boolean getCodeChallenge()Set totrueto enable Proof Key for Code Exchange (PKCE) for the authorization-code flow. The default isfalse.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.
Recommended for native applications: PKCE binds the authorization code to the application instance that initiated the flow, reducing the risk that an intercepted code can be redeemed by another client. Current OAuth security guidance requires PKCE for public clients and recommends it broadly.
- Returns:
- the value of the
CodeChallengeproperty
-
setCodeChallenge
public void setCodeChallenge(boolean value)Sets theCodeChallengeproperty; seegetCodeChallenge().- Parameters:
value- the new value
-
getCodeChallengeMethod
Selects the PKCE transformation used whenisgetCodeChallenge()true.Value Behavior
S256Sends a Base64URL-encoded SHA-256 digest of the code verifier. This is the default and recommended method.plainSends the code verifier itself as the challenge. Use only for compatibility with a provider that cannot supportS256.Avoid downgrading: If a provider rejects
S256, do not automatically retry withplainunless the provider is known and explicitly requires it.- Returns:
- the value of the
CodeChallengeMethodproperty
-
setCodeChallengeMethod
Sets theCodeChallengeMethodproperty; seegetCodeChallengeMethod().- Parameters:
value- the new value (notnull)
-
getEnableSecrets
public boolean getEnableSecrets()Controls automatic resolution of selected values from operating-system secure storage. The default isfalse.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.
Purpose: Secret specifications allow deployment-specific values to remain outside source code and configuration files. Although endpoints and client IDs are not normally secret, resolving them the same way can centralize application configuration. Platform availability: This feature depends on supported operating-system credential storage. Ensure the named credential exists and that the process identity has permission to read it.
- Returns:
- the value of the
EnableSecretsproperty
-
setEnableSecrets
public void setEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().- Parameters:
value- the new value
-
getFailureInfo
Contains diagnostic information whenisgetAuthFlowState()5. The value is cleared whenbegins a new flow.startAuth()Use this property for failures in the listener, redirect processing, network connection, or token exchange. Provider-declared authorization denial is represented by state
4and is normally available in.getAccessTokenResponse()Review before logging: Diagnostics can include URLs, response bodies, or request details. Remove authorization codes, tokens, client credentials, and personal information before storing or transmitting logs.
- Returns:
- the value of the
FailureInfoproperty (read-only)
-
getIncludeNonce
public boolean getIncludeNonce()Set totrueto include an OpenID Connectnonceparameter in the authorization request. The nonce is generated by Chilkat using the byte length specified by. The default isgetNonceLength()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 versus state:
nonceprotects the relationship between an OpenID Connect request and its ID token. OAuthstatecorrelates the browser callback with the initiating request and is used for CSRF protection. They are related security controls but are not interchangeable.- Returns:
- the value of the
IncludeNonceproperty
-
setIncludeNonce
public void setIncludeNonce(boolean value)Sets theIncludeNonceproperty; seegetIncludeNonce().- Parameters:
value- the new value
-
getListenPort
public int getListenPort()Specifies the local TCP port on which Chilkat listens for the browser's OAuth redirect. Choose an available nonprivileged port, typically between1024and65535.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
to selectgetLocalHost()localhostor127.0.0.1. - Include the final
/when registering the redirect URI.
Provider registration must match: Authorization servers differ in their support for loopback ports and redirect-URI matching. Register the exact form required by the provider. The IPv4 loopback literal
127.0.0.1is generally more predictable than resolvinglocalhost.- Returns:
- the value of the
ListenPortproperty
- Use
-
setListenPort
public void setListenPort(int value)Sets theListenPortproperty; seegetListenPort().- Parameters:
value- the new value
-
getListenPortRangeEnd
public int getListenPortRangeEnd()Defines the inclusive end of a local-listener port range that begins with. The default value ofgetListenPort()0disables range selection and uses onlyListenPort.When nonzero, Chilkat selects an available port in the inclusive range. For example,
ListenPort=55110andListenPortRangeEnd=55117permit ports55110through55117.Redirect registration: The provider must accept the selected redirect URI. If it requires every exact port to be pre-registered, register each port in the range. If the provider supports the native-app loopback convention with a variable port, follow its documented registration form.
Read
to determine which port was used.getListenPortSelected()- Returns:
- the value of the
ListenPortRangeEndproperty
-
setListenPortRangeEnd
public void setListenPortRangeEnd(int value)Sets theListenPortRangeEndproperty; seegetListenPortRangeEnd().- Parameters:
value- the new value
-
getListenPortSelected
public int getListenPortSelected()Returns the local port selected for the current or most recently completed authorization flow.When a range is configured with
, use this value to determine the actual loopback redirect port. It is also available for thegetListenPortRangeEnd(){listenPort}substitution supported by.getStateParam()- Returns:
- the value of the
ListenPortSelectedproperty (read-only)
-
getLocalHost
Selects the host name used in the loopback redirect URI:Value Redirect form
localhosthttp://localhost:{port}/127.0.0.1http://127.0.0.1:{port}/The default is
localhost. The value must match the redirect URI registered with the provider.Loopback recommendation:
127.0.0.1avoids DNS and hosts-file ambiguity and is generally preferable when the provider accepts an IPv4 loopback-literal redirect.- Returns:
- the value of the
LocalHostproperty
-
setLocalHost
Sets theLocalHostproperty; seegetLocalHost().- Parameters:
value- the new value (notnull)
-
getNonceLength
public int getNonceLength()Specifies the number of random bytes used to generate the hexadecimal OpenID Connect nonce whenisgetIncludeNonce()true. The resulting string contains two hexadecimal characters per byte.The default is
4bytes, which produces an 8-character hexadecimal nonce.Entropy matters: For security-sensitive OpenID Connect use, consider a substantially larger nonce, such as 16 bytes or more, unless the provider imposes a different requirement.
- Returns:
- the value of the
NonceLengthproperty
-
setNonceLength
public void setNonceLength(int value)Sets theNonceLengthproperty; seegetNonceLength().- Parameters:
value- the new value
-
getOob
public boolean getOob()Set totrueto use the legacy out-of-band redirect URIurn:ietf:wg:oauth:2.0:oob. The application must obtain the displayed authorization code and pass it to. The default isexchangeCodeForToken(String)false.Legacy and often unsupported: OOB authorization exposes a code for manual copy/paste and is no longer accepted by many providers. For desktop applications, use a loopback redirect with PKCE whenever possible.
- Returns:
- the value of the
Oobproperty
-
setOob
public void setOob(boolean value)Sets theOobproperty; seegetOob().- Parameters:
value- the new value
-
getRedirectAllowHtml
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.
Do not expose credentials: The HTML is shown in a browser. Do not insert the authorization code, access token, refresh token, client secret, or raw callback URL into this page.
- Returns:
- the value of the
RedirectAllowHtmlproperty
-
setRedirectAllowHtml
Sets theRedirectAllowHtmlproperty; seegetRedirectAllowHtml().- Parameters:
value- the new value (notnull)
-
getRedirectDenyHtml
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.
Denial is not a transport failure: User denial is represented by
valuegetAuthFlowState()4. It should normally be handled as a completed flow in which consent was not granted.- Returns:
- the value of the
RedirectDenyHtmlproperty
-
setRedirectDenyHtml
Sets theRedirectDenyHtmlproperty; seegetRedirectDenyHtml().- Parameters:
value- the new value (notnull)
-
getRedirectReqReceived
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.
Highly sensitive diagnostic data: The request can contain an authorization code, state value, provider identifiers, and browser metadata. Do not record it in production logs without careful redaction.
- Returns:
- the value of the
RedirectReqReceivedproperty (read-only)
-
getRefreshToken
Gets or sets the refresh token used to obtain new access tokens. Chilkat populates this property when the token endpoint issues arefresh_token, andreads it when creating a refresh request.refreshAccessToken()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.
Long-lived credential: Refresh tokens commonly outlive access tokens and can be used without user interaction. Protect them at least as carefully as passwords, persist replacements after rotation, and delete them when authorization is revoked.
- Returns:
- the value of the
RefreshTokenproperty
-
setRefreshToken
Sets theRefreshTokenproperty; seegetRefreshToken().- Parameters:
value- the new value (notnull)
-
getResource
Specifies an optional provider-definedresourceparameter 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.
Not a universal OAuth parameter: Set this property only when the authorization server documents a required
resourcevalue. Do not assume that an API base URL is always the correct value.- Returns:
- the value of the
Resourceproperty
-
setResource
Sets theResourceproperty; seegetResource().- Parameters:
value- the new value (notnull)
-
getResponseMode
Specifies the response mode requested from an OpenID Connect or provider-specific authorization endpoint.Set to
form_postto addresponse_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.Provider support required: Use only a response mode supported by the provider and compatible with Chilkat's local listener or intermediary callback.
- Returns:
- the value of the
ResponseModeproperty
-
setResponseMode
Sets theResponseModeproperty; seegetResponseMode().- Parameters:
value- the new value (notnull)
-
getResponseType
Specifies the authorization response type. The default iscode, which requests an authorization code.Set to
id_token+codewhen a provider requires the OpenID Connect hybrid responseresponse_type=id_token code; the plus sign is the URL-encoded representation of a SPACE in the query string.Prefer the code flow unless required otherwise: Hybrid responses add an ID token to the browser-facing authorization response and require correct OpenID Connect validation, including issuer, audience, signature, expiration, and nonce checks.
- Returns:
- the value of the
ResponseTypeproperty
-
setResponseType
Sets theResponseTypeproperty; seegetResponseType().- Parameters:
value- the new value (notnull)
-
getScope
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.
Provider-defined and consented: Scope names, separators, defaults, and offline-access requirements vary by provider. Request the minimum permissions needed and verify the granted scope returned in the token response.
- Returns:
- the value of the
Scopeproperty
-
setScope
Sets theScopeproperty; seegetScope().- Parameters:
value- the new value (notnull)
-
getStateParam
Allows the application to supply an explicit OAuthstatevalue. 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.Do not weaken state: State correlates the redirect with the initiating browser flow and helps prevent CSRF and authorization-response injection. If supplying your own value, make it unpredictable, unique per flow, and free of secrets or sensitive application data.
- Returns:
- the value of the
StateParamproperty
-
setStateParam
Sets theStateParamproperty; seegetStateParam().- Parameters:
value- the new value (notnull)
-
getTokenEndpoint
Specifies the provider's token endpoint. Chilkat sends authorization-code and refresh-token requests to this URL over TLS.Provider Authorization endpoint Token endpoint
Google
https://accounts.google.com/o/oauth2/v2/authhttps://oauth2.googleapis.com/tokenMicrosoft identity platform
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorizehttps://login.microsoftonline.com/{tenant}/oauth2/v2.0/tokenSalesforce production
https://login.salesforce.com/services/oauth2/authorizehttps://login.salesforce.com/services/oauth2/tokenQuickBooks Online
https://appcenter.intuit.com/connect/oauth2https://oauth.platform.intuit.com/oauth2/v1/tokens/bearerX API
https://x.com/i/oauth2/authorizehttps://api.x.com/2/oauth2/tokenBack-channel endpoint: Unlike the authorization endpoint, the token endpoint is contacted directly by the application, not opened in the user's browser. Use the provider's current HTTPS endpoint: Endpoint locations can change. Prefer the value published in the provider's OAuth or OpenID Connect metadata, and do not mix sandbox and production endpoints.
- Returns:
- the value of the
TokenEndpointproperty
-
setTokenEndpoint
Sets theTokenEndpointproperty; seegetTokenEndpoint().- Parameters:
value- the new value (notnull)
-
getTokenType
Contains thetoken_typevalue from the most recent successful token response. The common value isBearer.Use the returned type: OAuth does not require every token to use the same presentation mechanism. Follow the authorization server's documentation and the returned token type when constructing API requests.
- Returns:
- the value of the
TokenTypeproperty
-
setTokenType
Sets theTokenTypeproperty; seegetTokenType().- Parameters:
value- the new value (notnull)
-
getUncommonOptions
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_SCOPEOmits thescopeparameter from the authorization-code token request.ExchangeCodeForTokenUsingJsonSends the authorization-code token request as an HTTP POST with a JSON body instead of the normal form/query representation.RefreshTokenUsingJsonSends the refresh-token request as an HTTP POST with a JSON body.Leave empty unless required: These options alter interoperability behavior outside the normal OAuth token-request format. Enable one only when the provider's documentation or Chilkat support explicitly requires it.
- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
getUseBasicAuth
public boolean getUseBasicAuth()Controls howClientIdandClientSecretare supplied during the authorization-code token exchange.Value Behavior
trueSends HTTP Basic authentication using the client ID as the username and the client secret as the password.falseSends the client ID and client secret as request parameters. This is the default.Match the provider's client-authentication method: Some authorization servers require HTTP Basic authentication; others require parameters or no client secret for public clients. A wrong choice usually produces an
invalid_clientresponse. TLS is mandatory: Both forms expose the secret to the token endpoint. They differ in HTTP representation, not in the need for a secure TLS connection.- Returns:
- the value of the
UseBasicAuthproperty
-
setUseBasicAuth
public void setUseBasicAuth(boolean value)Sets theUseBasicAuthproperty; seegetUseBasicAuth().- Parameters:
value- the new value
-
addAuthQueryParam
Adds a name/value query parameter to the authorization URL produced by. Call the method multiple times to add multiple provider-specific authorization parameters.startAuth()Typical examples include provider extensions such as
access_type=offline,prompt=consent, or an account-selection hint.Do not add secrets: Authorization parameters are placed in a URL and can appear in browser history, proxy logs, and diagnostics. Never put a client secret, access token, refresh token, or other credential in an authorization query parameter.
- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addRefreshQueryParam
Adds a provider-specific name/value parameter to requests sent by. Call the method multiple times to add multiple parameters.refreshAccessToken()Use only when documented: Chilkat automatically supplies the standard refresh-token grant parameters. Additional parameters are provider extensions and should be added only when required by the authorization server.
- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says 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
orstartAuth(); it does not alter the browser authorization URL or refresh-token requests.exchangeCodeForToken(String)Nonstandard extension: The normal authorization-code request parameters are generated automatically. Use this method only for an additional parameter documented by the provider, and do not duplicate standard parameters such as
grant_type,code, orredirect_uriunless instructed by Chilkat support.- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
cancel
public void cancel()Requests cancellation of the authorization flow currently running in the background thread.Returns
trueif the cancellation request is accepted. After cancellation, inspectandgetAuthFlowState()to determine the final state.getFailureInfo()Scope of cancellation: This stops the local authorization operation. It does not revoke an access token, refresh token, authorization grant, or consent that the provider has already issued.
- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
exchangeCodeForToken
Exchanges the authorization code incodefor tokens at.getTokenEndpoint()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
. Configure the same client, endpoint, redirect, PKCE, and token-request settings that the provider requires for the original authorization request.getOob()On success, the token properties and
are populated in the same manner as a successful background exchange.getAccessTokenResponse()Legacy OOB flow: Many major providers no longer accept
urn:ietf:wg:oauth:2.0:oob. Prefer an authorization-code flow with a loopback redirect and PKCE whenever the provider supports it.- Parameters:
code- thecodeargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getAccessTokenResponseSb
Copies the raw token-endpoint response intosband returnstrueon success.This is the
StringBuilderequivalent of reading. The response is commonly JSON, but some providers return form-encoded or other text; this method does not guarantee JSON.getAccessTokenResponse()Contains credentials: The response can contain an access token and refresh token. Treat the destination
StringBuilderas sensitive data and avoid logging or exposing its contents.- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getRedirectRequestParam
Returns the decoded value ofparamNamefrom 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, anderrorvalues. For example, QuickBooks can return a company identifier namedrealmId:http://localhost:55568/?state=...&code=...&realmId=1234567890
Provider extensions: OAuth defines the core redirect parameters, but providers may add their own values. Consult the provider's documentation before depending on an additional parameter. Sensitive redirect data: Authorization codes and related callback parameters are credentials or security-sensitive correlation values. Avoid writing them to ordinary application logs.
- Parameters:
paramName- theparamNameargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
launchBrowser
Asks the operating system to openurlin 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
. ReturnsstartAuth()falseif the operating system cannot launch a browser or open the URL.No browser automation: This method only opens the URL. Chilkat does not control the browser, enter credentials, approve consent, or close the browser window.
- Parameters:
url- theurlargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
refreshAccessToken
public void refreshAccessToken()Sends a refresh-token grant request toto obtain a new access token without repeating interactive browser authorization.getTokenEndpoint()Configure
,getClientId(), andgetRefreshToken(), together with whatever client authentication the provider requires. This may includegetTokenEndpoint()andgetClientSecret().getUseBasicAuth()On success, Chilkat updates
,getAccessToken(), andgetTokenType(). If the provider rotates refresh tokens and returns a newgetAccessTokenResponse()refresh_token,is also updated.getRefreshToken()Persist rotated refresh tokens: Some providers invalidate the old refresh token as soon as a new one is issued. After a successful refresh, securely persist the current value of
RefreshTokenrather than assuming the previous value remains usable. Provider-specific requests: UseandsetRefreshHeader(String, String)only when the provider documents additional headers or parameters.addRefreshQueryParam(String, String)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setRefreshHeader
Adds or replaces an HTTP request header used by subsequent calls to.refreshAccessToken()nameis the header field name andvalueis its value.Call this method once for each required header. Passing an empty
valueremoves the named header.Accept: application/json
Normally unnecessary: Standard OAuth refresh requests do not require application-defined headers beyond those generated by the client. Add headers only when the authorization server explicitly requires them, and never place access tokens, refresh tokens, or client secrets in diagnostic headers.
- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sleepMs
public void sleepMs(int millisec)Suspends the calling thread formillisecmilliseconds.This convenience method is commonly used in a polling loop that checks
while the authorization flow continues on Chilkat's background thread.getAuthFlowState()Thread behavior: The calling thread is blocked for the requested interval. In a graphical application, use the platform's normal asynchronous or timer mechanism when blocking the UI thread would make the application unresponsive.
- Parameters:
millisec- themillisecargument
-
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
,getClientId(),getAuthorizationEndpoint(), the requestedgetTokenEndpoint(), and the redirect-listener settings such asgetScope(). ConfiguregetListenPort()only when the provider requires client authentication for this application type.getClientSecret()- 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
or another browser-launch mechanism. PolllaunchBrowser(String)until the flow reaches a terminal state.getAuthFlowState()PKCE and client authentication: Enabling
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. Failure detection: String-returning bindings return an empty or null-equivalent value on failure. Check the normal method-success indicator and inspectgetCodeChallenge()LastErrorTextbefore attempting to open the returned URL.- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
useConnection
Associatessockwith 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.
Browser traffic is separate: This socket controls Chilkat's back-channel token requests. It does not configure the user's browser, the provider's authorization page, or the browser's redirect to the local listener.
- Parameters:
sock- thesockargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- Pass an unconnected
-
setProgressListener
Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.- Parameters:
listener- the listener, ornull- Throws:
IllegalStateException- if called from inside one of this object's own callbacks
-
getProgressListener
Returns the installed listener, ornull.- Returns:
- the listener installed with
setProgressListener(ProgressListener)or one of theon...methods
-
onAbortCheck
Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onPercentDone
Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onProgressInfo
Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-