OAuthClient
Wisej.NET 4.2.0+
OAuthClient signs a user in with an external identity provider — Google, GitHub, Microsoft Entra ID, GitLab, or any OAuth 2.0 / OpenID Connect server — and publishes the result as an OAuthIdentity on Application.User. It runs the authorization-code flow with PKCE, validates everything the provider sends back on the server, and keeps the tokens it receives out of reach of everything but GetAccessToken.
Choose it when your users already have an account with one of those providers and you would rather not store passwords, or when the application needs an access token to call the provider's own APIs (Microsoft Graph, Google APIs, GitHub). To let users sign in with a fingerprint or a security key instead, see Passkey; the two work well together.
OAuthClient is a non-visual component: drop it on a page or form and it appears in the designer's component tray.
For a complete list of properties, methods, and events, see the API documentation.
What the component does for you
The protocol details that make OAuth sign-in safe are not settings. The component always does them:
- PKCE (S256) on every provider that accepts it, so an intercepted authorization code is useless without the verifier that never leaves the server.
- State: a single-use value made of 43 characters from a cryptographic source, bound to the attempt and compared on return. A callback whose state does not match is refused.
- Issuer check: the RFC 9207
issparameter on the callback is compared with the provider the attempt was sent to, which defeats provider mix-up attacks. - Nonce and ID token validation for OpenID Connect providers: the signature is always checked against the provider's published keys, then
iss,aud,azp,exp,nbf, the nonce and, where they apply, Google'shdand Entra'stid. - Browser binding in Redirect mode: a cookie ties the attempt to the browser that started it, so a callback URL replayed in another browser fails.
- HTTPS only: every provider endpoint, and the redirect URI, must be
httpsunless its host is a loopback address. There is no opt-out. - A new session id after every sign-in and sign-out, so a session id captured before the login is worthless after it (see Session Fixation).
- No secrets in messages: no error message, log line or
ToString()ever contains a code, state, nonce, PKCE verifier, token or client secret.
Quick start
- Drop an
OAuthClienton your login page and setProviderandClientIdin the property grid. - Run the application once and read
ResolvedRedirectUri: it is the exact redirect URI to register with the provider (see OAuth Providers). - Register an application with the provider using that URI, and give the component the client secret through one of the secret sources — never in the designer.
- Call
SignIn()from a button, and handleAuthenticatedandAuthenticationFailed.
public partial class LoginPage : Page
{
public LoginPage()
{
InitializeComponent();
// set in the designer, shown here for clarity.
this.oAuthClient1.Provider = OAuthProvider.Google;
this.oAuthClient1.ClientId = "<your-client-id>.apps.googleusercontent.com";
}
private void buttonSignIn_Click(object sender, EventArgs e)
{
this.oAuthClient1.SignIn();
}
private void oAuthClient1_Authenticated(object sender, OAuthAuthenticatedEventArgs e)
{
// the user is signed in: switch views here.
Application.MainPage = new MainPage();
}
private void oAuthClient1_AuthenticationFailed(object sender, OAuthAuthenticationFailedEventArgs e)
{
// e.Message is localized and safe to show; e.ErrorDescription is for the log only.
AlertBox.Show(e.Message, MessageBoxIcon.Error, allowHtml: false);
Trace.TraceWarning("Sign-in failed: {0} {1} {2}", e.Reason, e.Error, e.ErrorDescription);
}
}
SignIn() returns true when the user was sent to the provider and false when the attempt was canceled by a SigningIn handler or failed configuration checks — in which case AuthenticationFailed has already been raised. It throws InvalidOperationException in design mode or on a thread with no Wisej session.
The signed-in user
After a successful sign-in the component assigns an OAuthPrincipal to Application.User, so Application.IsAuthenticated is true everywhere in the session. The principal wraps an OAuthIdentity, which derives from ClaimsIdentity:
var principal = Application.User as OAuthPrincipal;
if (principal != null)
{
OAuthIdentity identity = principal.Identity;
var key = identity.Provider + ":" + identity.Subject; // the stable account key
this.labelName.Text = identity.DisplayName;
this.pictureBoxAvatar.ImageSource = identity.Picture;
var locale = identity.FindFirst("locale")?.Value; // any provider claim
var isAdmin = principal.IsInRole("admin"); // roles added in Authenticating
}
| Member | What it holds |
|---|---|
Subject | The provider's stable identifier for the user: Google sub, GitHub id, Entra oid, GitLab sub, a custom provider's sub. Also present as a ClaimTypes.NameIdentifier claim. |
Email, EmailVerified | The provider's email claim, and whether the provider asserts it is verified. Entra never makes that assertion, so EmailVerified is always false there. |
DisplayName, GivenName, FamilyName, Picture | Profile data, or null. For GitHub, DisplayName is the user's name, falling back to the login. |
TenantId | The Entra tid claim, or Google's hd (hosted domain) claim, or null. |
Issuer, AuthenticatedAt, Provider | Where and when the user signed in. |
RawUserInfo, RawIdTokenClaims | The validated documents as a DynamicObject, for anything the properties do not surface. |
Use Provider and Subject to find the user's record in your database. An email address can change, can be reassigned, and is not always verified — Entra never asserts it is. Linking accounts by email is how one person ends up signed in as another.
OAuthIdentity carries no token of any kind and holds no reference back to the component, so it is safe to log, bind to a grid or pass to another layer. The component also exposes the same identity on its own Identity property, and IsAuthenticated tells you whether it holds one.
If the host has already authenticated the user — Windows authentication, or ASP.NET Core cookie authentication — the component does not overwrite that principal by default: it logs a note and leaves Application.User alone. Set e.SetApplicationUser to true in Authenticating to replace it knowingly.
Flow modes
FlowMode decides how the user reaches the provider in the browser.
Redirect (default) | Popup | |
|---|---|---|
| What the user sees | The tab navigates to the provider and comes back | A popup window opens on the provider and closes itself |
| Where the provider returns | The application's own page | A relay page embedded in Wisej.Framework: resource.wx/Wisej.Framework/OAuthCallback.html under the application root |
| The application's tab | Reloads; the user interface is re-rendered | Never leaves; the session keeps running |
OAuthCallbackSource | Redirect | Popup |
Can await SignInAsync() be relied on | Only while the session survives the round trip | Yes |
| Requires cookies | Yes | No |
| If the popup is blocked | — | The attempt restarts as a full-page redirect against the same relay URI |
Why events, not an awaited task, in Redirect mode
In Redirect mode the browser leaves your application. If the user takes a long time at the provider — a forgotten password, a multi-factor prompt on a phone — the Wisej session can expire. The provider then returns to your page, a new session starts, Program.Main runs again, and a new component tree is built. The pending attempt is not lost: it is kept in an application-wide store, and the OAuthClient on the new page claims it and finishes the sign-in. The user notices nothing.
What cannot survive is a Task that code in the old session was awaiting. So:
- Put the code that runs after sign-in in the
Authenticatedhandler, not afterawait SignInAsync(). - Make sure the page that hosts the
OAuthClientis created when the application starts — the pageProgram.Mainshows — so the new session has a component to receive the callback. - Keep the component's
Name(the designer sets it) the same: an arriving callback is claimed by the component whose name matches the one that started it.
OAuthAuthenticatedEventArgs.Source tells you how the answer arrived; Redirect means the user interface was re-rendered and, if the session had been evicted, that the component tree is brand new.
When the session survives, the callback completes in Application.ApplicationRefresh; when it did not, in Application.ApplicationStart. Both end in Authenticated. If your application's sessionTimeout is shorter than 600 seconds, the component logs a warning: a value of 0, or at least 600, keeps the session alive through a multi-factor prompt. See Session Management.
The attempt is bound to the browser that started it through a short-lived cookie (__Host- prefixed when the redirect URI is https). A browser that blocks cookies, or a callback URL opened in a different browser, fails with OAuthError.InvalidState.
Popup mode
// oAuthClient1.FlowMode is set to Popup in the designer.
private async void buttonSignIn_Click(object sender, EventArgs e)
{
try
{
var identity = await this.oAuthClient1.SignInAsync();
this.labelWelcome.Text = "Welcome, " + identity.DisplayName;
}
catch (OAuthException ex)
{
// AuthenticationFailed has been raised as well.
AlertBox.Show(ex.Message, MessageBoxIcon.Error, allowHtml: false);
}
catch (TaskCanceledException)
{
// CancelSignIn() or SignInTimeout.
}
}
The relay page never loads the Wisej client; it passes the result back to the opener and closes. Call SignIn or SignInAsync from a user action such as a button click, so the browser lets the popup open. If it is blocked anyway, the attempt restarts as a redirect against the same relay URI — which is why only one URI per flow mode has to be registered with the provider. An application hosted cross-site inside an iframe cannot take that restart and is not supported in Popup mode.
Always await SignInAsync() or GetAccessTokenAsync(). Calling .Result or .Wait() on them deadlocks: client events run under the session lock, and the task needs that same session to complete. async void event handlers are fine in Wisej.NET.
SignInAsync() returns a Task<OAuthIdentity> that completes after Authenticated, faults with an OAuthException after AuthenticationFailed, and is canceled by CancelSignIn() or by SignInTimeout (600 seconds by default, between 30 and 3600). One task can be outstanding per component; calling SignIn again discards the previous attempt and cancels its task.
Events
The events are raised in this order during a sign-in:
SignIn()
1. ProviderResolved endpoints known; patch them (once per configuration)
2. SigningIn adjust this attempt, or cancel it
--> browser goes to the provider, user signs in, provider returns a code
--> server exchanges the code, validates the ID token, reads userinfo
3. Authenticating decide whether this user gets in; edit claims and roles
--> tokens stored, Application.User assigned, session id renewed
4. Authenticated the user is signed in: switch views
(or AuthenticationFailed at any point instead)
Later:
TokenExpired an access token was needed and could not be renewed
SignedOut the local sign-out has finished
ProviderResolved
Raised once the provider's endpoints are known — from a built-in preset or from a discovery document — and before they are used. OAuthProviderResolvedEventArgs lets you change Issuer, AuthorizationEndpoint, TokenEndpoint, UserInfoEndpoint, JwksUri, RevocationEndpoint, EndSessionEndpoint, DefaultScopes, SubjectClaim and NameClaimType; IsDiscovered and Metadata show where the values came from. Values you assign win, are checked exactly like the preset ones (non-empty, https), and are cached with the component. The event is raised again when Provider, ClientAuthenticationMethod, Tenant or Authority changes, and when a discovered document is more than 24 hours old. Use it for custom providers, proxied token endpoints and national clouds — see OAuth Providers.
SigningIn
Raised before the user is sent to the provider. OAuthSignInEventArgs exposes this attempt's mutable Scopes list and Parameters collection, and settable Prompt, LoginHint, DomainHint, RedirectUri and FlowMode. LoginHint exists only here, on purpose: a hint is right for one user, and a designer value would be sent for every user of the form.
private void oAuthClient1_SigningIn(object sender, OAuthSignInEventArgs e)
{
// pre-fill the account the user typed on our own login page.
e.LoginHint = this.textBoxEmail.Text;
// ask for one more permission on this attempt only.
e.Scopes.Add("https://www.googleapis.com/auth/calendar.readonly");
}
e.Cancel = truestops the attempt. It is not reported throughAuthenticationFailed— the application ended it itself — andSignIn()returnsfalse.e.Handled = truemeans your code navigates the user itself, usinge.AuthorizationUri, and will callCompleteSignInwith the callback. See Custom hosts and launchers.e.Parameters(pre-filled from theAuthorizationParametersproperty) overrides computed parameters such asscope,prompt, the hints,access_typeandresponse_mode. The seven protocol parameters —state,nonce,code_challenge,code_challenge_method,client_id,redirect_uriandresponse_type— cannot be overridden; such entries are ignored with a warning.
Authenticating
Raised after the provider's answer has been fully validated and before the user becomes Application.User. This is the authorization decision point: check the user against your own records, edit claims, add roles, or refuse.
private void oAuthClient1_Authenticating(object sender, OAuthAuthenticatingEventArgs e)
{
// application code: the application's own user table, looked up by provider and subject.
var account = AccountRepository.Find(e.Provider, e.Identity.Subject);
if (account == null || account.IsDisabled)
{
e.Cancel = true;
e.Reason = "No active account for this user."; // becomes ErrorDescription
return;
}
// roles become claims of the identity's role claim type, so IsInRole finds them.
e.Principal = new OAuthPrincipal(e.Identity, account.Roles);
// any other claim the application needs.
e.Identity.AddClaim(new Claim("account_id", account.Id.ToString()));
}
| Member | Use |
|---|---|
Identity | The OAuthIdentity that was built. Add, remove or remap claims on it. The computed Email, DisplayName and TenantId properties were read at construction and do not change. |
Principal | The principal to assign. Defaults to a new OAuthPrincipal; assign new OAuthPrincipal(e.Identity, roles) to add roles, or another IPrincipal. Null is not allowed. |
SetApplicationUser | Whether Application.User is assigned. Set it to false for a second component that only collects API tokens and must not replace the signed-in user. |
Cancel, Reason | Refuse the user. The attempt fails with OAuthError.Rejected and Reason as its ErrorDescription. |
Canceling Authenticating stores nothing from this attempt, and it leaves any earlier sign-in on the component exactly as it was. To end a sign-in already in effect — a user you have just disabled — call SignOut() yourself.
The new tokens are stored only after Authenticating approves, so GetAccessToken cannot be used from inside this handler to call the provider's API for the user being decided on.
Authenticated
Raised last, when the user is signed in. Switch views here. OAuthAuthenticatedEventArgs carries the Provider, the Identity, the Principal that was assigned, IsApplicationUser (whether this component assigned Application.User) and the Source.
AuthenticationFailed
The single failure channel for every stage: the component never throws out of a callback. Raised for any attempt that ends without a sign-in, except one a SigningIn handler canceled. See Errors.
TokenExpired and SignedOut
See Calling APIs and Signing out.
Calling APIs with the access token
There is deliberately no AccessToken property. Call GetAccessToken() or GetAccessTokenAsync() each time you need a token: they return the stored token, refreshing it first when it is within 60 seconds of expiry and a usable refresh token is stored. Refreshes are single-flight, so twenty concurrent callers produce one token request.
private static readonly HttpClient Http = new HttpClient();
private async void buttonLoadProfile_Click(object sender, EventArgs e)
{
var token = await this.oAuthClient1.GetAccessTokenAsync();
if (token == null)
return; // could not be renewed: TokenExpired has been raised.
using (var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me"))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var response = await Http.SendAsync(request))
{
this.textBoxProfile.Text = await response.Content.ReadAsStringAsync();
}
}
}
GetAccessToken()throws anOAuthExceptionwhen the component is not signed in, and returns null afterTokenExpiredwas raised.- The synchronous
GetAccessToken()andRefreshAccessToken()are safe to call from an event handler: they wait only on the HTTP request. RefreshAccessToken()forces a refresh now — after the API answered 401, for instance — and rotates the refresh token when the provider returns a new one. The 60-second margin is not configurable.TokenExpiresAtandGrantedScopesdescribe the current token.GetIdToken()returns the raw, validated ID token of the current sign-in, for a downstream service that re-validates it.
Refresh tokens and OfflineAccess
Set OfflineAccess to true to ask the provider for a refresh token, so the application can keep calling APIs after the first access token expires (typically after an hour). How it is asked for differs per provider — see OAuth Providers. A refresh token is kept whenever the provider returns one, whatever OfflineAccess says, and every sign-in replaces the stored token set.
TokenExpired
Raised when a token was needed and could not be renewed. The identity stays signed in by default, so an hour-old login without offline access does not silently log the user out; only API access is gone.
OAuthTokenExpiredReason | Meaning | Stored tokens |
|---|---|---|
NoRefreshToken | The access token expired and there is no usable refresh token: none was issued, or it has expired. | Cleared |
RefreshRejected | The provider refused the refresh: the grant was revoked, the password changed, the refresh token expired. | Cleared |
ProviderUnavailable | A network failure, timeout or 5xx during the refresh. | Kept, so you can retry |
private void oAuthClient1_TokenExpired(object sender, OAuthTokenExpiredEventArgs e)
{
if (e.Reason == OAuthTokenExpiredReason.ProviderUnavailable)
return; // tokens kept: try again later.
// the application cannot work without API access: sign the user out.
e.SignOut = true;
}
e.SignOut = true runs a local sign-out with OAuthSignOutReason.TokenExpired, without revocation and without the provider hop. To send the user through the provider's sign-out page instead, leave it false and call SignOut(signOutAtProvider: true) yourself.
Signing out
this.oAuthClient1.SignOut(revokeTokens: true, signOutAtProvider: true,
postLogoutRedirectUri: "https://app.example.com/Default.html");
SignOut assigns an OAuthAnonymousPrincipal to Application.User, clears the tokens and Identity, discards any pending attempt, renews the session id and raises SignedOut. It returns when revocation (if requested) and the local sign-out are done; only the navigation to the provider happens afterwards. It is safe to call when not signed in; no events fire then.
| Parameter | Effect |
|---|---|
revokeTokens | Revoke the access and refresh tokens at the provider before clearing them. Best-effort: the outcome is SignedOut's TokensRevoked, never AuthenticationFailed. Entra has no revocation endpoint. |
signOutAtProvider | Navigate the tab to the provider's end-session endpoint afterwards, ending the user's session there too. Ignored when the provider has none: only Entra and custom OpenID Connect providers do. |
postLogoutRedirectUri | Where the provider sends the user afterwards. Null sends the explicit RedirectUri when one is set, otherwise nothing — and Entra then shows its own signed-out page. Register this URI with the provider. |
OAuthSignedOutEventArgs reports Reason, TokensRevoked, ProviderSignOutPending (an end-session navigation is queued) and ApplicationUserCleared. The component never calls Application.Exit(); show what your application shows to signed-out users in the handler.
Sign-out assigns OAuthAnonymousPrincipal rather than null on purpose: assigning null makes Application.User fall back to the host's principal, which would leave the user authenticated under Windows or cookie authentication.
Client id and secret
ClientId and the client secret are each resolved by a chain that stops at the first non-empty value:
- The
ClientIdorClientSecretproperty. - The environment variable
WISEJ_OAUTH_<PROVIDER>_CLIENT_IDorWISEJ_OAUTH_<PROVIDER>_CLIENT_SECRET, where<PROVIDER>is the provider name upper-cased:GOOGLE,GITHUB,ENTRA,GITLABorOAUTH2. Application.Configuration.Settings.oauth.<provider>.clientIdor.clientSecret, with the provider name lower-cased, read from thesettingssection of the application's configuration file.- The JSON file named by the environment variable
WISEJ_OAUTH_SECRETS_FILE.
A resolved value is used for one request and is never written back to the property, kept in a field, logged or sent to the browser. If no secret can be resolved for a provider that needs one, the attempt fails with OAuthError.Configuration, and ErrorDescription names the environment variable that was looked for — the name, never a value. With ClientAuthenticationMethod set to OAuthClientAuthenticationMethod.None the secret chain does not run at all.
ClientSecret is hidden from the property grid and never serialized by the designer, so a secret cannot end up in your .Designer.cs file by accident.
The configuration file is the natural home of the client id, which is not a secret:
{
"url": "Default.html",
"startup": "MyApp.Program.Main, MyApp",
"settings": {
"oauth": {
"google": { "clientId": "<your-client-id>.apps.googleusercontent.com" },
"entra": { "clientId": "<application-client-id-guid>" }
}
}
}
The secrets file lives outside the web root and has the same shape as the settings.oauth section, so moving credentials between the two is a copy:
{
"google": { "clientId": "<client-id>", "clientSecret": "<client-secret>" },
"github": { "clientId": "<client-id>", "clientSecret": "<client-secret>" },
"entra": { "clientId": "<client-id>", "clientSecret": "<client-secret>" }
}
The file is read on each request that needs it and nothing from it is cached. A file that is missing or does not parse is logged once — naming the variable and the exception type, never the path — and the chain ends there.
The configuration file sits in the web root. Reading a secret from it is safe only because every Wisej.NET template refuses requests for *.json files; a custom host that drops that rule serves your secret to anyone who asks. Prefer the environment variables or the secrets file for the client secret.
Reading the secret from a vault
ResolveClientSecret (and ResolveClientId) are protected virtual methods. Override ResolveClientSecret in a derived component to read the secret from Azure Key Vault, AWS Secrets Manager or any other store:
public class VaultOAuthClient : OAuthClient
{
protected override string ResolveClientSecret()
{
// application code: a secret the application loaded from its vault at startup.
var secret = AppSecrets.Get("oauth-" + this.Provider.ToString().ToLowerInvariant());
// fall back to the built-in chain when the vault has nothing for this provider;
// return null without calling base to skip the fallbacks.
return secret ?? base.ResolveClientSecret();
}
}
The override runs on the session thread for the code exchange, for each refresh and for the revocation that SignOut(revokeTokens: true) performs. An exception it throws is caught: the request fails with OAuthError.Configuration (on a refresh, TokenExpired with ProviderUnavailable), and the exception travels on the event arguments with its messages scrubbed — it is never logged.
Errors
OAuthAuthenticationFailedEventArgs.Reason and OAuthException.Reason are an OAuthError. Show e.Message to the user — it is a localized, safe string. e.Error, e.ErrorDescription, e.ErrorUri and e.HttpStatus are for you and your logs: provider text on the callback can be influenced by an attacker, so never show ErrorDescription to an end user.
OAuthError | What happened | What to do |
|---|---|---|
Canceled | CancelSignIn() was called, or the user closed the popup. | Nothing; let the user try again. |
Timeout | The attempt exceeded SignInTimeout. | Let the user try again; raise SignInTimeout if your users need longer at the provider. |
AccessDenied | The user declined consent or canceled at the provider. | Explain why the permissions are needed and offer to try again. |
ProviderError | The provider returned another error on the callback. | Read Error and ErrorDescription in the log: often a scope the registration does not allow, or a misconfigured redirect URI. |
InvalidState | The state or iss did not match, or the callback came from a browser that did not start the attempt. | Possible forgery or replay — do not retry automatically. Also seen when cookies are blocked in Redirect mode, or a callback link was opened in another browser. |
Expired | A callback arrived with no matching attempt, or after it expired — including the browser's back button onto an old callback URL, and a server restart while the user was at the provider. | Let the user start again. |
TokenRequestFailed | The token endpoint refused the code, or the request failed. | Check HttpStatus and Error: usually a wrong client secret, a redirect URI that differs from the registered one, or an expired code. |
InvalidToken | The ID token failed validation, or for Entra its tenant is not in AllowedTenants. | Check the issuer, the clock of the server, and AllowedTenants. |
UserInfoRequestFailed | The userinfo request (GitHub's /user) failed or returned no usable subject. | Check the scopes; for a custom provider, check SubjectClaim. |
Rejected | Your Authenticating handler canceled. ErrorDescription is the Reason you set. | Tell the user why they cannot sign in. |
Configuration | Missing or inconsistent configuration. ErrorDescription names the check that failed. | Fix what it names: no client id, no resolvable secret, None for Google or GitHub, a non-https redirect URI or endpoint, a launcher host with no launcher, an Entra Authority/Tenant conflict, an AllowedTenants entry that is not a tenant id, a discovery document that cannot be fetched or publishes the wrong issuer. |
Unknown | Any other exception. | See e.Exception. |
Extensibility
OAuthClient is designed to be derived from. Every step of the pipeline has a protected virtual method:
| Method | Override to |
|---|---|
CreateHttpClient() | Supply a proxy, a handler chain, a different timeout or User-Agent, or a test double. The default is one shared client with a 10-second timeout. |
CreateAuthorizationUri(request) | Build the authorization URI for a provider with an unusual parameter set. |
ExchangeCodeAsync(code, request, cancellationToken) | Route the code exchange through a proxy or a non-standard token endpoint. |
ValidateIdTokenAsync(idToken, request, cancellationToken) | Change ID token validation. The base implementation always checks the signature, with a fixed 300-second clock skew. |
RequestUserInfoAsync(tokens, cancellationToken) | Fetch the user document differently. |
CreateIdentity(claims, subject, name) | Return a subclass of OAuthIdentity. |
RefreshTokenCoreAsync(cancellationToken) | Perform the refresh grant differently. |
RevokeTokensCoreAsync(cancellationToken) | Revoke tokens at a provider with its own mechanism. |
CreateEndSessionUri(postLogoutRedirectUri) | Build the provider's logout URI. |
ResolveClientId(), ResolveClientSecret() | Read credentials from your own store. |
Each On<Event> method (OnAuthenticating, OnAuthenticated, ...) can be overridden as well. OAuthTokenResponse.Raw, which an ExchangeCodeAsync or RefreshTokenCoreAsync override sees, contains the tokens: never log it.
Custom hosts and launchers
Three seams cover hosts where the browser tab is not how the user reaches the provider:
IOAuthLauncher: a host that opens the provider outside the browser — a native shell using the system browser, as Wisej.NET Hybrid apps do — registers an implementation withApplication.Services. The component resolves it at sign-in, asksCanHandle(), and when it answerstrueprefers it over both flow modes.LaunchAsyncopens the authorization URI and returns the callback's parameters, or null when the user canceled. No launcher ships with Wisej.NET 4.2.0; the interface is there so hosts can provide one.SigningInwithe.Handled = true: your code takese.AuthorizationUri, navigates the user its own way, and callsCompleteSignIn(Uri)orCompleteSignIn(NameValueCollection)with the callback. The attempt stays pending until then, untilCancelSignIn(), or until it times out.GetAuthorizationUri(): runs the same preparation asSignIn—ProviderResolved, validation,SigningIn— and returns the URI without navigating, for an application-rendered link or a test.
// application code: the host's own launcher, implementing both members of the interface.
public class SystemBrowserLauncher : IOAuthLauncher
{
public bool CanHandle()
{
return NativeShell.IsAvailable;
}
public Task<NameValueCollection> LaunchAsync(Uri authorizationUri, Uri callbackUri, CancellationToken cancellationToken)
{
// open authorizationUri in the system browser, wait for the provider to return to
// callbackUri, and return its query parameters - or null if the user canceled.
return NativeShell.AuthenticateAsync(authorizationUri, callbackUri, cancellationToken);
}
}
// at startup:
Application.Services.AddService<IOAuthLauncher, SystemBrowserLauncher>();
On the launcher path the component computes no redirect URI: set RedirectUri explicitly — a custom scheme such as com.example.app:/oauth is accepted there and only there. OAuthClientAuthenticationMethod.None is allowed for a launcher host, which usually has no safe place for a secret. CompleteSignIn runs the same validation as every other path, with OAuthCallbackSource.Launcher; a callback for a Redirect attempt is still held to the browser that started it.
See Dependency Injection for registering services.
Security notes
- Tokens are reachable only through methods. The access token comes from
GetAccessToken, the ID token fromGetIdToken; neither is a property, so neither appears in a property grid, data binding or reflection dump. The refresh token is never exposed at all.OAuthIdentitycarries no tokens. - Show
Message, logErrorDescription. Provider text on the callback is attacker-influenceable;Messageis the framework's own string. - Decide authorization in
Authenticating. Signing in with Google proves the user owns a Google account, nothing more. Check the account against your own records, the Entra tenant, or the Google hosted domain before letting the user in. - Restrict Google Workspace sign-ins with
DomainHint, not with a rawhdentry inAuthorizationParameters: onlyDomainHintis enforced against the ID token'shdclaim. - Restrict multi-tenant Entra sign-ins with
AllowedTenants. Without it,commonandorganizationsadmit every Microsoft tenant in the world. See OAuth Providers. - Keep the client secret off the web root and out of source control — see Client id and secret.
- Set
RedirectUriexplicitly behind a TLS-terminating proxy. The computed value is built from the request the server sees, which ishttpthere, and the component refuses anhttpredirect URI on a non-loopback host. - Changing
Provider,ClientId,TenantorAuthoritydiscards the stored tokens: they were issued for the previous configuration and are never sent anywhere else. The identity stays signed in;GetAccessTokenreturns null until the next sign-in. - Use
Application.Userfor authorization checks on the server, not a flag kept in a control. See Security.