Customer sign-in from a .NET app
How your .NET web app signs in the people who use it (your customers), with TenancyEngine as the identity provider. This page states the supported contract, shows a complete recipe, and lists what you must validate on every sign-in.
Requires TenancyEngine.Sdk 2.3.0 or later from nuget.org. Items marked released are in the 2.3.0 package. Items marked source only exist in the repository but are not on nuget.org; do not depend on them yet (see the changelog).
What exists today
| Piece | Status | What it does |
|---|---|---|
TenancyEngineOidcContract (TenancyEngine.Sdk.Oidc) | released | Constants of the sign-in contract: client type, PKCE method, callback paths, scopes. |
TenancyEngineOidcClientCheck | released | Probe for a /health/oidc endpoint. Checks that your authority, client id and redirect URI are accepted by the platform. |
TenancyEngineIdentityProviderOutageMiddleware | released | Shows a controlled page when the identity provider is unreachable. |
TenancyEngineClient.GetRuntimeContextAsync | released | Returns the Authority, ClientId and ApiBaseUrl registered for your app and environment. |
Lane table and TenancyEngineIssuerResolver | source only (2.4 to 2.11) | Resolves the issuer from the platform lane table. |
| An ASP.NET Core sign-in handler | not provided | Planned as a separate package, TenancyEngine.Sdk.AspNetCore, tracked in tenancyengine#1576. Until it ships, you register the standard ASP.NET Core OpenID Connect handler yourself, as below. |
The released SDK does not validate the application, environment or tenant of a signed-in person. The checklist below is your code today.
The contract
Your app signs people in through a public client registered for your application. The values come from TenancyEngineOidcContract:
- Client id: your application slug. The paired confidential client
{slug}-serveris for server-to-server calls and is never used for sign-in. - Authorization-code flow (
response_type=code) with PKCES256. - No client secret. The token endpoint uses client authentication
none. Configuring a secret for this client makes the platform reject the code exchange (OpenIddict ID2053). - Callback path
/signin-oidc, sign-out callback/signout-callback-oidc. The full redirect URIs must be registered on your application environment in the TenancyEngine console. - Scopes:
openid,profile,email,api.
Get the authority from the platform
Do not paste an authority host into code. Your app already holds an API key and an API base URL for every other SDK call (see API key scopes; this call needs applications.read). At startup, ask the platform which authority and client id are registered for the environment the app runs in:
using TenancyEngine.Sdk;
using var http = new HttpClient { BaseAddress = new Uri(builder.Configuration["TenancyEngine:ApiBaseUrl"]!) };
var te = new TenancyEngineClient(http, apiKey: builder.Configuration["TenancyEngine:ApiKey"]!);
var runtime = await te.GetRuntimeContextAsync(
builder.Configuration["TenancyEngine:AppSlug"]!,
builder.Configuration["TenancyEngine:Environment"]!) // "Development", "Staging" or "Production"
?? throw new InvalidOperationException("The platform does not know this app and environment.");
var authority = runtime.Authority
?? throw new InvalidOperationException("No authority registered for this environment.");
var clientId = runtime.ClientId;Authority is the value stored on the application environment. When it is blank, the platform answers with its own default authority for the lane it runs in (ApplicationProductContractService, ResolveDefaultAuthority). The base URL, key and environment name are per-deployment configuration, as for the rest of the SDK.
Run TenancyEngineOidcClientCheck.RunAsync behind a /health/oidc endpoint. It catches a mismatched client id, a stray secret or an unregistered redirect URI without needing a user account.
Recipe: cookie session with OpenID Connect
builder.Services
.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(o =>
{
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Lax;
o.ExpireTimeSpan = TimeSpan.FromMinutes(30); // see "Sessions and revocation"
o.SlidingExpiration = false;
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, o =>
{
o.Authority = authority;
o.ClientId = clientId;
o.ClientSecret = null; // public client: PKCE only
o.ResponseType = "code";
o.UsePkce = true;
o.CallbackPath = TenancyEngineOidcContract.CallbackPath;
o.SignedOutCallbackPath = TenancyEngineOidcContract.SignedOutCallbackPath;
o.SaveTokens = true;
o.GetClaimsFromUserInfoEndpoint = false; // the id token already carries the claims below
o.MapInboundClaims = false; // keep claim names as issued: sub, tenant_id, permission
o.TokenValidationParameters.NameClaimType = "name";
o.TokenValidationParameters.RoleClaimType = "role";
o.Scope.Clear();
foreach (var scope in TenancyEngineOidcContract.Scopes) o.Scope.Add(scope);
o.Events.OnTokenValidated = ctx =>
{
var rejection = TenantClaimChecks.Validate(ctx.Principal!, expected);
if (rejection is not null) ctx.Fail(rejection);
return Task.CompletedTask;
};
});expected is your own configuration: your application id (runtime.ApplicationId) and the environment name. For a staff-only area, also the tenant that holds your staff (see App staff authorization).
Validate on every sign-in
The platform puts these claims in the access token and the id token (OidcTokenClaimDestinations):
| Claim | Meaning | Your check |
|---|---|---|
sub | The person. | Required. |
application_id | The application the sign-in was issued for. | Must equal your application id. Reject otherwise. |
environment | Development, Staging or Production. | Must equal the environment you run in. Reject if absent: it is only present when a tenant environment was resolved. |
tenant_id, tenant_slug | The tenant the person signed in to. | Must be present for customer sign-in. Use it as the tenant key on every query; never take the tenant from the request. |
role | The person's role in that tenant. | Informational; authorize on permission. |
permission | JSON array of the permission keys the role grants. Omitted when the role has none. | Authorize on it. A missing claim means no permissions. |
organization_id, organization_role | Present only when tenant_id is absent: a TenancyEngine organization login, not a customer. | A customer area must reject any token without tenant_id. |
PlatformClaimsService builds these claims and AppRoleClaimService builds permission.
static class TenantClaimChecks
{
public sealed record Expected(string ApplicationId, string Environment);
public static string? Validate(ClaimsPrincipal p, Expected e)
{
if (p.FindFirst("application_id")?.Value != e.ApplicationId) return "Wrong application.";
if (p.FindFirst("environment")?.Value != e.Environment) return "Wrong environment.";
if (!Guid.TryParse(p.FindFirst("tenant_id")?.Value, out _)) return "No tenant on this sign-in.";
if (p.FindFirst("sub") is null) return "No subject.";
return null;
}
// The claim is a JSON array. The OpenID Connect handler normally expands it to one claim per
// value; this also accepts the raw array form.
public static IReadOnlySet<string> Permissions(ClaimsPrincipal p) =>
p.FindAll("permission")
.SelectMany(c => c.Value.TrimStart().StartsWith('[')
? JsonSerializer.Deserialize<string[]>(c.Value) ?? []
: [c.Value])
.ToHashSet(StringComparer.Ordinal);
}Sessions and revocation
With the contract's scopes the app receives no refresh token, so the platform is not consulted again after sign-in. The upper bound on how long a removed person or a changed role stays in effect is your cookie lifetime: choose it deliberately and set SlidingExpiration to false. If you request a refresh token, the platform re-validates application, organization and tenant membership on every refresh-token grant (AuthorizationController), and you should re-run the checks above on each refresh. There is no token introspection endpoint to call per request.
Not yet provided
- A released ASP.NET Core package that does the above (discovery, claim validation, permission policies). Tracked in tenancyengine#1576.
- A released helper that rejects a token whose application, environment or tenant is not yours.
- Per-request revocation of a signed-in person.