Skip to main content
Version: 4.2

OAuthClient

Namespace: Wisej.Web

Assembly: Wisej.Framework (4.2.0.0)

Signs a user in with Google, GitHub, GitLab, Microsoft Entra ID or any OAuth 2.0 / OpenID Connect provider using the authorization-code flow with PKCE, and publishes the result as an OAuthIdentity on User.

4.2.0+
public class OAuthClient : Component

Drop the component on a page, set Provider and ClientId, read ResolvedRedirectUri to learn exactly what to register with the provider, then call SignIn. Wire Authenticated and AuthenticationFailed rather than awaiting SignInAsync when FlowMode is Redirect: the callback can land in a brand-new session against a brand-new component tree, where no awaited task exists. Redirect mode requires cookies: the attempt is bound to the browser that started it, and a callback presented by another browser fails with InvalidState.

Constructors​

Instance member OAuthClient()​

Initializes a new instance of the OAuthClient class.

Instance member OAuthClient(container)​

Initializes a new instance of the OAuthClient class together with the specified container.

NameTypeDescription
containerIContainerAn IContainer that represents the container for the component.

Properties​

Instance member AllowedTenants​

String[]: Returns or sets the permitted tenant identifiers for a multi-tenant Entra registration. (Default: null)

Enforced before any claim is trusted: a token whose tid is not listed fails with InvalidToken. Null with a multi-tenant alias as the effective tenant — Tenant, or the Authority path segment when Tenant is empty — accepts every Microsoft tenant and writes one log warning per component instance naming this property. Ignored when the effective tenant pins a specific tenant.

Each entry is a tenant ID: a GUID, compared by value, so its letter case and spelling do not matter. A verified domain is not accepted here, because the ID token names its tenant by ID only: when the list is in force, an entry that is not a GUID fails the sign-in with Configuration naming this property, before the user is sent to the provider. Null and empty entries are ignored.

Instance member Authority​

String: Returns or sets the provider authority: the discovery root of a custom provider, the GitHub Enterprise Server or GitLab host, or the Microsoft Entra instance. (Default: null)

For Entra this is the Entra instance: null means https://login.microsoftonline.com; a national cloud is its host, https://login.microsoftonline.us; and the MSAL authority shape https://login.microsoftonline.com/{tenant} is accepted when Tenant is empty, the single path segment becoming the tenant (a segment equal to a non-empty Tenant is no conflict). A segment that differs from a non-empty Tenant fails at sign-in with Configuration naming both properties; two or more segments, or a query or fragment, fail naming this property. Parsed when the descriptor is resolved, not on set.

A change discards the stored tokens: they were issued by the previous authority and are never sent to another one. The identity stays signed in; GetAccessToken returns null until the next sign-in.

Instance member AuthorizationParameters​

NameValueCollection: Returns or sets additional authorization parameters; null resets the collection.

An entry overrides the computed parameter of the same name - scope, prompt, the hints, access_type, response_mode - except the seven protocol parameters state, nonce, code_challenge, code_challenge_method, client_id, redirect_uri and response_type, which the component computes and later checks: those entries are ignored with a warning.

Instance member ClientAuthenticationMethod​

OAuthClientAuthenticationMethod: Returns or sets the client authentication method for token requests. (Default: ClientSecretPost)

Instance member ClientId​

String: Returns or sets the client identifier registered with the provider. (Default: null)

A change discards the stored tokens: they were issued to the previous client and are never sent with another one. The identity stays signed in; GetAccessToken returns null until the next sign-in.

Instance member ClientSecret​

String: Returns or sets the confidential client secret used only on the server. (Default: null)

Instance member DomainHint​

String: Returns or sets the provider domain hint. For Google, the hd claim of the ID token is enforced against the value sent. (Default: null)

Google: sent as hd, and the ID token's hd claim must equal the value sent with the attempt — DomainHint when a handler set one, else this property — so the restriction is enforced, not merely suggested; a raw hd entry in AuthorizationParameters is not enforced. Entra: sent as domain_hint. Ignored by GitHub, GitLab and OAuth2.

Instance member FlowMode​

OAuthFlowMode: Returns or sets whether browser sign-in uses a redirect or a popup. (Default: Redirect)

Instance member GrantedScopes​

String[]: Returns the scopes granted by the provider.

Instance member Identity​

OAuthIdentity: Returns the identity from the last successful sign-in.

Instance member IsAuthenticated​

Boolean: Returns whether this component holds an authenticated identity.

Instance member IsSigningIn​

Boolean: Returns whether this component has a pending sign-in request.

Instance member Name​

String: Returns or sets the name of the OAuthClient.

Value: A string representing the name of the component. The default is an empty string ("").

Not inherited. Component declares no Name property — only Control does — so this component declares its own over the framework's internal naming helpers, as Menu and DataGridViewColumn do. The pending-attempt store's claim predicate reads this value to route a callback back to the right component instance after the originating session was evicted.

Instance member OfflineAccess​

Boolean: Returns or sets whether to request offline access. (Default: False)

Every sign-in replaces the stored token set, the refresh token included. Google issues a refresh token only when it asks for consent: with Prompt left at Default or set to Consent the component sends prompt=consent, but with None, Login or SelectAccount an account that has already consented gets none, and the component then holds no refresh token even if an earlier sign-in had one.

Instance member Prompt​

OAuthPrompt: Returns or sets the requested provider interaction. (Default: Default)

Instance member Provider​

OAuthProvider: Returns or sets the identity provider to authenticate against. (Default: Google)

A change discards the pending sign-in attempt and the stored tokens: they were issued by the previous provider and are never sent to another one. The identity stays signed in; GetAccessToken returns null until the next sign-in.

Instance member RedirectUri​

String: Returns or sets the exact redirect URI registered with the provider. (Default: null)

Instance member RequestUserInfo​

Boolean: Returns or sets whether to request user information after token exchange. (Default: False)

Instance member ResolvedRedirectUri​

String: Returns the exact redirect URI for the current configuration, or an empty string outside a runtime session.

At the origin root the value is the origin plus the entry page the application configuration names - Configuration.Url, for example "/Default.html" - because the root is where Wisej resolves the root configuration and can therefore name that page. Returns null in the three cases where no entry page can be named: the origin root with no application configuration, or one naming no page; a folder root other than the origin root, which each host rewrites differently; and a final path segment with no file extension. That value is not registrable: the provider would honour it and return the user to a URL that cannot complete the sign-in. A warning naming the problem and the fix is written to the log, once per component. An explicit RedirectUri is not subject to this check and is what the launcher path uses too, custom schemes included.

Instance member Scopes​

String[]: Returns or sets the requested scopes, or null to use the provider defaults. (Default: null)

Instance member SignInTimeout​

Int32: Returns or sets the sign-in attempt lifetime in seconds. (Default: 600)

Instance member Tag​

Object: Returns or sets application-defined data associated with the component. (Default: null)

Instance member Tenant​

String: Returns or sets the Microsoft Entra tenant: a tenant ID, a verified domain of the tenant, or one of the multi-tenant aliases "common", "organizations" and "consumers". (Default: "common")

A tenant ID is a GUID in any letter case; the component uses its lower-case form, which is how Entra writes it in the ID token's iss and tid claims. A verified domain, such as contoso.onmicrosoft.com, is sent to Entra as set, and resolved to its tenant ID for token validation through the tenant's OpenID Connect metadata on the configured instance - the document Entra publishes at {instance}/{domain}/v2.0/.well-known/openid-configuration, fetched when the first sign-in completes and cached for twenty-four hours. A domain whose metadata cannot be fetched or names no tenant ID fails the sign-in with Configuration.

A change discards the stored tokens: they were issued by the previous tenant and are never sent to another one. The identity stays signed in; GetAccessToken returns null until the next sign-in.

Instance member TokenExpiresAt​

Nullable<DateTimeOffset>: Returns the UTC access-token expiry, when supplied by the provider.

Methods​

Instance member CancelSignIn()​

Discards the pending attempt, cancels the task returned by SignInAsync and raises AuthenticationFailed with Canceled. No-op when nothing is pending.

An open popup is closed only when the browser allows it. While the popup shows the provider's page, browsers ignore the request and the popup stays open; finishing the sign-in there after the cancel does not sign the user in.

Instance member CompleteSignIn(callbackUri)​

Feeds a provider callback that arrived by some other route: a launcher, a custom host route, or a test.

ParameterTypeDescription
callbackUriUriThe full callback URI, including its query and fragment.

Returns: Boolean. true when the user was signed in.

Runs the same pipeline as the built-in delivery paths with Launcher. Every failure except a missing attempt surfaces through AuthenticationFailed rather than as an exception. A redirect attempt is held to its browser binder here as on the automatic paths: a callback presented by a browser that did not start it fails with InvalidState and the attempt stays pending. Safe to call from a request thread: the callback is already in hand and the method waits on the token and userinfo requests only.

Throws:

Instance member CompleteSignIn(parameters)​

Feeds a provider callback that arrived by some other route: a launcher, a custom host route, or a test.

ParameterTypeDescription
parametersNameValueCollectionThe callback parameters, as name/value pairs.

Returns: Boolean. true when the user was signed in.

Runs the same pipeline as the built-in delivery paths with Launcher. Every failure except a missing attempt surfaces through AuthenticationFailed rather than as an exception. A redirect attempt is held to its browser binder here as on the automatic paths: a callback presented by a browser that did not start it fails with InvalidState and the attempt stays pending. Safe to call from a request thread: the callback is already in hand and the method waits on the token and userinfo requests only.

Throws:

Protected member CreateAuthorizationUri(request)​

Builds the authorization URI for an attempt. Override for a provider with an unusual parameter set. PKCE S256 is always included when the descriptor supports it; an override that must omit it also overrides ExchangeCodeAsync.

ParameterTypeDescription
requestOAuthAuthorizationRequestThe pending attempt.

Returns: Uri. The authorization URI.

Protected member CreateEndSessionUri(postLogoutRedirectUri)​

Builds the RP-initiated logout URI.

ParameterTypeDescription
postLogoutRedirectUriStringWhere the provider returns after logout: the SignOut argument, else the explicit RedirectUri, else null — in which case no post_logout_redirect_uri is appended.

Returns: Uri. The end-session URI, or null when the provider has none.

The parameter is the plumbing for the SignOut argument. The fallback reads the raw RedirectUri PROPERTY, which is empty under the computed default, so with no argument and no explicit RedirectUri nothing is sent - AppendUriParameter skips empties - and Entra lands the user on its own signed-out page; the argument, not the fallback, is what keeps the landing page, and Entra keeps post-logout URIs in a separate registration list anyway.

Protected member CreateHttpClient()​

Returns the HttpClient used for every provider call. Override this to supply a proxy, a handler chain, or a test double.

Returns: HttpClient. The shared client, configured with a 10-second timeout and the User-Agent "Wisej.NET/<framework version> Wisej.Web" — which GitHub requires. The default implementation returns one process-wide instance that must not be disposed by the caller. Override for a proxy, a handler chain, a different timeout or a custom User-Agent; neither value is a property.

Protected member CreateIdentity(claims, subject, name)​

Builds the identity. Override to return a subclass of OAuthIdentity.

ParameterTypeDescription
claimsIList<Claim>The assembled claims, before Authenticating.
subjectStringThe chosen subject.
nameStringThe chosen display name, resolved from the descriptor's name-claim candidates. It is not written into any claim: the wire "name" claim stands, and DisplayName reads it.

Returns: OAuthIdentity. The identity.

Protected member Dispose(disposing)​

Releases the resources used by this component.

ParameterTypeDescription
disposingBooleantrue when called by the application rather than a finalizer.

Protected member ExchangeCodeAsync(code, request, cancellationToken)​

Exchanges the authorization code for tokens. Override to route the exchange through a proxy or to support a non-standard token endpoint. The returned Raw is the only place application code sees the raw token document.

ParameterTypeDescription
codeStringThe authorization code.
requestOAuthAuthorizationRequestThe attempt the code belongs to.
cancellationTokenCancellationTokenCancels the request.

Returns: Task<OAuthTokenResponse>. The token response.

Throws:

Instance member GetAccessToken()​

Returns a usable access token, refreshing it transparently when it is within 60 seconds of expiry and a usable refresh token is stored.

Returns: String. The bearer token, or null after TokenExpired was raised because it could not be renewed.

This is the only way to read a bearer token: there is deliberately no AccessToken property. Refreshes are single-flight, so concurrent callers share one token request. The refresh margin is not configurable; call RefreshAccessToken to force a refresh at a moment of the application's choosing — after a 401, for instance.

Throws:

Instance member GetAccessTokenAsync()​

Returns a usable access token, refreshing it transparently when it is within 60 seconds of expiry and a usable refresh token is stored.

Returns: Task<String>. The bearer token, or null after TokenExpired was raised because it could not be renewed.

This is the only way to read a bearer token: there is deliberately no AccessToken property. Refreshes are single-flight, so concurrent callers share one token request. The refresh margin is not configurable; call RefreshAccessToken to force a refresh at a moment of the application's choosing — after a 401, for instance.

Throws:

Instance member GetAuthorizationUri()​

Prepares an attempt and returns the authorization URI without navigating, for custom launchers, application-rendered links and tests.

Returns: Uri. The authorization URI.

Runs the same preparation as SignIn — ProviderResolved, validation, attempt creation, SigningIn — and leaves the attempt pending. Set RedirectUri explicitly when calling this from a test, to avoid depending on the application's startup URL.

Instance member GetIdToken()​

Returns the raw, validated ID token of the current sign-in, or null when there is none.

Returns: String. The compact JWT as the provider issued it; null when not signed in or when the provider issued no ID token with the current sign-in - never one from an earlier sign-in. Unchanged by refresh. Re-validate downstream.

A method, not a property, so the token never appears in a property grid, data binding or a reflection dump.

Protected member OnApplicationRefresh(sender, e)​

Handles ApplicationRefresh. Completes a redirect callback that arrived into the session that started it.

ParameterTypeDescription
senderObjectThe application.
eEventArgsEvent data.

Protected member OnApplicationStart(sender, e)​

Handles ApplicationStart. Completes a redirect callback that arrived into a session created after the original one was evicted.

ParameterTypeDescription
senderObjectThe application.
eEventArgsEvent data.

Protected member OnAuthenticated(args)​

Fires the Authenticated event.

ParameterTypeDescription
argsOAuthAuthenticatedEventArgs

Protected member OnAuthenticating(args)​

Fires the Authenticating event.

ParameterTypeDescription
argsOAuthAuthenticatingEventArgs

Protected member OnAuthenticationFailed(args)​

Fires the AuthenticationFailed event.

ParameterTypeDescription
argsOAuthAuthenticationFailedEventArgs

Protected member OnProviderResolved(args)​

Fires the ProviderResolved event.

ParameterTypeDescription
argsOAuthProviderResolvedEventArgs

Protected member OnSignedOut(args)​

Fires the SignedOut event.

ParameterTypeDescription
argsOAuthSignedOutEventArgs

Protected member OnSigningIn(args)​

Fires the SigningIn event.

ParameterTypeDescription
argsOAuthSignInEventArgs

Protected member OnTokenExpired(args)​

Fires the TokenExpired event.

ParameterTypeDescription
argsOAuthTokenExpiredEventArgs

Protected member OnWebEvent(e)​

Processes an event from the client.

ParameterTypeDescription
eWisejEventArgsEvent arguments.

Protected member OnWebRender(config)​

Provides the client widget's configuration.

ParameterTypeDescription
configObjectThe configuration.

Instance member RefreshAccessToken()​

Forces a refresh of the access token and rotates the stored refresh token when the provider returns a new one.

Returns: Boolean. true on success, with the new access token stored, TokenExpiresAt updated and any rotated refresh token kept; false on failure, with TokenExpired raised.

Single-flight with GetAccessToken. Blocks on the refresh request only, which is safe on a request thread.

Throws:

Protected member RefreshTokenCoreAsync(cancellationToken)​

Performs the refresh-token grant. The returned Raw is the only place application code sees the raw refresh response.

ParameterTypeDescription
cancellationTokenCancellationTokenCancels the request.

Returns: Task<OAuthTokenResponse>. The new token set.

Protected member RequestUserInfoAsync(tokens, cancellationToken)​

Fetches the userinfo document.

ParameterTypeDescription
tokensOAuthTokenResponseThe tokens from the exchange.
cancellationTokenCancellationTokenCancels the request.

Returns: Task<Object>. The userinfo document as a DynamicObject.

Protected member ResolveClientId()​

Resolves the client id. Override to plug in a configuration source without handling an event.

Returns: String. The client id, or null.

The chain runs in this order and stops at the first non-empty value:

  1. the ClientId property;
  2. the environment variable WISEJ_OAUTH_<PROVIDER>_CLIENT_ID, where <PROVIDER> is the OAuthProvider member name upper-cased - GOOGLE, GITHUB, ENTRA or OAUTH2;
  3. Application.Configuration.Settings.oauth.<provider>.clientId, with the provider name lower-cased. The settings bag is read from the entry page's .json in the web root. It is safe only because every shipped Wisej 4 template refuses *.json (the HttpForbiddenHandler on .NET Framework, the UseWhen(!".json") predicate on ASP.NET Core); a custom host must keep that guard, or the file is one GET away. Prefer the environment variable or the secrets file for the secret.
  4. the JSON secrets file named by the WISEJ_OAUTH_SECRETS_FILE environment variable.

Nothing is resolved in design mode, where the ClientId property value is returned unchanged. The resolved value is used for one request and is never written back to ClientId.

Protected member ResolveClientSecret()​

Resolves the client secret for one request. The base implementation runs the four-link chain — ClientSecret, the environment variable, application settings, the secrets file. Override to plug in a vault; return null without calling the base to skip the fallbacks. The returned value is used for that one request and is never written back to ClientSecret; an exception thrown by an override is caught at the call site and the request fails with Configuration, the exception carried — pattern-scrubbed by OAuthRedaction, never written to the log — on Exception or, on a refresh, on Exception.

Returns: String. The client secret, or null.

The chain runs in this order and stops at the first non-empty value:

  1. the ClientSecret property;
  2. the environment variable WISEJ_OAUTH_<PROVIDER>_CLIENT_SECRET, where <PROVIDER> is the OAuthProvider member name upper-cased;
  3. Application.Configuration.Settings.oauth.<provider>.clientSecret, with the provider name lower-cased. The settings bag is read from the entry page's .json in the web root. It is safe only because every shipped Wisej 4 template refuses *.json (the HttpForbiddenHandler on .NET Framework, the UseWhen(!".json") predicate on ASP.NET Core); a custom host must keep that guard, or the file is one GET away. Prefer the environment variable or the secrets file for the secret.
  4. the JSON secrets file named by the WISEJ_OAUTH_SECRETS_FILE environment variable.

This override is the vault seam: an override that returns a value wins, and an override that returns null without calling the base skips the fallbacks - the attempt then fails with Configuration when the provider requires a secret. Called on the session thread before the first await of the code exchange, and re-entered into the session for the refresh and for the revocation run by SignOut(revokeTokens: true), because a vault handler may touch session state and links 3 and 4 read request-scoped configuration.

Nothing is resolved in design mode, where the ClientSecret property value is returned unchanged. A null return fails the attempt with Configuration and a message naming the environment variable - never the value, never a partial value and never a length. The resolved value is used for one request, is never written back to ClientSecret, is never retained in a field or a static, and is never rendered to the client or written to the log.

Instance member ResolveDescriptorAsync(cancellationToken)​

Resolves the endpoints for the current provider, from a preset or by discovery, raising ProviderResolved once per descriptor.

ParameterTypeDescription
cancellationTokenCancellationTokenCancels any discovery fetch.

Returns: Task<OAuthProviderDescriptor>. The resolved descriptor.

The order is fixed and each step depends on the one before it: a private copy of the preset row, the per-provider quirk branch that substitutes the authority, instance and tenant placeholders - and, for Entra, parses Authority in its two shapes - the discovery fetch and its issuer check when a needed endpoint is still empty, and finally ProviderResolved, whose handler outranks everything and whose edits - the endpoints, the issuer, the default scopes, the subject claim and the name claim - are cached with the descriptor. The event is the only public way to patch the descriptor.

PKCE is never gated on discovery metadata. Entra supports S256 and publishes no code_challenge_methods_supported member, so a metadata gate would silently disable PKCE against the one provider whose documentation most insists on it. The static profile in OAuthProviderDescriptor decides, and its only exception is a GitHub Enterprise Server authority.

Threading: the session is captured before the discovery await, because everything after a ConfigureAwait(false) runs off-session, where every Application write is a silent no-op against the process-wide shared instance. The capture is CaptureResolutionContext rather than the ambient thread, because this method is not always entered on a session thread: the sign-out, refresh and revoke paths in OAuthClient.Tokens.cs reach it after their own ConfigureAwait(false), and ProviderResolved is a public seam, so it may touch session state whichever path resolved the descriptor. The event is raised with RunInContext and never with Update: on the sign-in paths this runs inside a client request, where a response is already being built, and on the sign-out path the caller owns the push.

Protected member RevokeTokensCoreAsync(cancellationToken)​

Performs provider-specific revocation.

ParameterTypeDescription
cancellationTokenCancellationTokenCancels the request.

Returns: Task<Boolean>. true when the provider accepted the revocation.

Instance member SignIn()​

Starts the authorization-code flow. Any previous pending attempt on this component is discarded and its task canceled.

Returns: Boolean. true when the user was sent to the provider or handed to a launcher; false when the attempt was canceled by a SigningIn handler or failed configuration validation. A false return is always accompanied by AuthenticationFailed except when a handler canceled.

Throws:

Instance member SignInAsync()​

Starts the authorization-code flow and returns a task that completes with the signed-in identity.

Returns: Task<OAuthIdentity>. A task that completes after Authenticated, faults with an OAuthException after AuthenticationFailed, or is canceled by CancelSignIn or SignInTimeout.

Always await this task; never block on .Result, because client events run under the session lock and blocking deadlocks. The task is a reliable completion signal in Popup mode and on the launcher path. In Redirect mode it is reliable only while the caller's session survives the round trip: if the session was evicted the callback completes in a new session where this task does not exist, and Authenticated is the only signal. One outstanding task per component. Redirect mode requires cookies: the attempt is bound to the browser that started it, and a callback presented by another browser fails with InvalidState.

Instance member SignOut(revokeTokens, signOutAtProvider, postLogoutRedirectUri)​

Signs the user out locally, with optional revocation at the provider and an optional navigation to the provider's end-session endpoint.

ParameterTypeDescription
revokeTokens optionalBooleantrue to revoke the access and refresh tokens at the provider before they are cleared. Best-effort; the outcome is TokensRevoked.
signOutAtProvider optionalBooleantrue to navigate the tab to the provider's end-session endpoint after the local sign-out. Ignored when the provider has none.
postLogoutRedirectUri optionalStringThe post_logout_redirect_uri sent to the end-session endpoint. Null sends the explicit RedirectUri when one is set, otherwise none.

Assigns an OAuthAnonymousPrincipal to User, clears the stored tokens and Identity, discards any pending attempt and raises SignedOut. The method blocks until revocation (when requested) and the local sign-out are done; only the end-session navigation happens after it returns. Safe to call when not signed in; no events fire then.

Protected member ValidateIdTokenAsync(idToken, request, cancellationToken)​

Validates the ID token and returns its claims. The base implementation always checks the signature against the resolved key set with a fixed 300-second clock skew; this override is the only way to change either, and the documented test seam (the QA TestOAuthClient overrides it).

ParameterTypeDescription
idTokenStringThe raw ID token.
requestOAuthAuthorizationRequestThe attempt, which carries the expected nonce.
cancellationTokenCancellationTokenCancels any key-set fetch.

Returns: Task<Object>. The validated claims as a DynamicObject.

Throws:

Events​

Instance member Authenticated​

OAuthAuthenticatedEventHandler Fired when the user is signed in. Switch views here.

Instance member Authenticating​

OAuthAuthenticatingEventHandler Fired before the user becomes Application.User. Edit claims, replace the principal, or veto.

Instance member AuthenticationFailed​

OAuthAuthenticationFailedEventHandler Fired when an attempt ends unsuccessfully, for any reason. An attempt that a SigningIn handler canceled is not reported: the application ended it itself.

Instance member ProviderResolved​

OAuthProviderResolvedEventHandler Fired when the provider's endpoints have been resolved and can still be patched.

Instance member SignedOut​

OAuthSignedOutEventHandler Fired when the local sign-out has finished.

Instance member SigningIn​

OAuthSignInEventHandler Fired before the user is sent to the provider. Scopes, parameters, prompt and hints are mutable.

Instance member TokenExpired​

OAuthTokenExpiredEventHandler Fired when the access token cannot be renewed. The identity stays signed in unless the handler opts out.

Implements​

NameDescription
IUserDataProvides access to the UserData and Tag properties associated to the component implementing this interface.
IWisejComponentAll wisej components implement this interface.
IWisejSerializableAllows an object to serialize itself.