Skip to content

Web app access-token check (.NET) ​

For an ASP.NET Core app that signs people in with TenancyEngine through an OIDC cookie session and wants to know, on a sensitive request, that the user's saved access token is genuine, meant for this app, and still honoured by the platform. TenancyEngineWebAppAuthority (TenancyEngine.Sdk 2.16.0, namespace TenancyEngine.Sdk.Oidc) does the local verification and then the platform check in one call.

It is the web-app counterpart of AddTenancyEngineMcpResource (which verifies bearer tokens on a resource server) and it sits on top of TenancyEngineCurrentAuthorityChecker (the introspection check from 2.12.0). Use it instead of writing your own JWT code and your own introspection POST.

What the platform issues: the written answer ​

Source references are to origin/featurewave at b0b81374.

1. Does an access token issued to a web client (confidential or public PKCE) carry exactly one audience equal to the app's registered resource? Only when the authorize request names that resource. It is not automatic, and it does not depend on whether the client is confidential or public (no code on these paths looks at the client type).

  • The resource is the API base URL of one active environment of the application (ApplicationEnvironment.ApiBaseUrl), matched ordinally: no trailing-slash, case or sibling-path tolerance, and an identifier that resolves to more than one application is treated as unregistered (ResourceIndicatorService.FindRegisteredAsync, src/TenancyPlatform.Infrastructure/OAuthMetadata/ResourceIndicatorService.cs:48-79).
  • Exactly one resource per request (ResourceIndicatorService.cs:85-88). A client that belongs to an application may request only its own application's resource (FirstPartyClientPolicy.MayRequestResourceAsync, src/SaaSRuntime.Api/Security/FirstPartyClientPolicy.cs:109-119).
  • When it passes, the access token's audience is replaced by exactly that one resource (ResourceIndicatorService.Bind, ResourceIndicatorService.cs:138-149, principal.SetResources(registration.Resource)), and the grant is refused with access_denied unless the user already has a workspace (tenant_id) in the resource's application (BindForAuthorization, ResourceIndicatorService.cs:155-162). The binding is applied at the authorize endpoint (src/SaaSRuntime.Api/Controllers/AuthorizationController.cs:170-205, with the pipeline gate in src/SaaSRuntime.Api/Security/ResourceIndicatorHandlers.cs:32-58) and re-applied on every refresh (AuthorizationController.cs:468, BindForRefreshResourceIndicatorService.cs:168-178). A resource on the token request must equal the one the grant was bound to; it can never change it (CheckTokenRequestResources, ResourceIndicatorService.cs:218-227, called at AuthorizationController.cs:323). So the ASP.NET code exchange (which sends no resource) and a refresh (which needs none) keep the binding.
  • The access token is a signed at+jwt, not encrypted (src/SaaSRuntime.Api/Program.cs:791, DisableAccessTokenEncryption). The platform's own verifier accepts only RS256, typ at+jwt, the configured issuer and a current lifetime (src/SaaSRuntime.Api/Security/AccessTokenSignatureVerifier.cs:62-76), and reads client_id, scope, tenant_id and a single aud from it (AccessTokenSignatureVerifier.cs:86-98). tenant_id and sub reach the access token and the ID token alike (src/TenancyPlatform.Infrastructure/Services/OidcTokenClaimDestinations.cs:12-24), which is why an ID token can look like a token with the right claims: its aud is the client id and its typ is JWT, and this helper refuses it on both counts.

2. What happens when the authorize request omits resource? The request is an ordinary platform grant. The token's audience then comes from the requested scopes' OpenIddict scope entries (src/TenancyPlatform.Infrastructure/Services/OidcPrincipalBuilderService.cs:65-67): the platform api scope maps to the resource saasruntime_api (src/TenancyPlatform.Infrastructure/Persistence/PlatformDbSeed.cs:305), and a request with only scopes that have no resource gets no aud at all (the comment at PlatformDbSeed.cs:236-245 records the same). Such a token never carries your resource. It also cannot name a scope an application published for its resource server (ValidateScopesWithoutResourceAsync, ResourceIndicatorService.cs:195-209, called at AuthorizationController.cs:182). This helper rejects it (wrong_audience), and so does the platform's introspection (foreign_audience: the audience must be an active environment of the calling app, src/SaaSRuntime.Api/Security/CurrentAuthorityService.cs:86-119).

3. How does an app get a conforming token? Send resource=<your registered API base URL> on the authorize request, with scopes limited to openid, offline_access and the resource scopes you registered for that application. Other scopes, including profile, email and the platform api scope, are invalid_scope for a resource-bound request (ResourceIndicatorService.cs:94-99). The user must already be a member of a workspace in the application. See the sample below.

Other facts that matter to a cookie-session app:

  • A resource-bound token never authenticates on SaaSRuntime's own APIs (RejectResourceBoundTokensHandler, Program.cs:829). Use it for your API and for this check; keep calling platform APIs with your API key.
  • Lifetimes. The access token lives one hour by default (an organization session policy can only shorten it; Program.cs:779 extends it to 7 days in Development only). The refresh token lives 14 days, does not slide, and has no reuse leeway (Program.cs:762-767): refresh from one place at a time.
  • Not validated here, by design: a DPoP-bound token (cnf claim). A cookie session cannot supply the proof, so the helper refuses it.

Register and configure ​

  1. Register the environment's API base URL (Applications, your application, Environments). That exact string is your Resource (https, no query, no fragment).
  2. Register the resource scopes your API understands, and create an application-level API key holding only oauth.introspect (see App access path for registering the application, its OAuth client and scopes).
  3. Register https://<your app>/signin-oidc and your post-logout redirect (https://<your app>/signout-callback-oidc by default) on the OAuth client.
  4. Configure the OIDC handler to request the resource, keep the tokens and handle a user with no workspace. The whole sample on this page (the Program.cs block and the refresher below) is compiled against the real APIs by the SDK test suite.
csharp
// file: Program.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TenancyEngine.Sdk.Oidc;

var builder = WebApplication.CreateBuilder(args);

const string Resource = "https://api.myapp.example";    // the registered ApiBaseUrl of the environment, character for character
const string Issuer = "https://auth.saasruntime.com";   // the lane's issuer: one value for iss, discovery, JWKS and introspection
const string ClientId = "myapp-web";
var introspectionKey = builder.Configuration["TenancyEngine:IntrospectionKey"];   // from your secret store, never from source

builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<WebAppTokenRefresher>();
builder.Services.AddSingleton(new WebAppTokenRefresherSettings(Issuer + "/connect/token", ClientId, builder.Configuration["TenancyEngine:ClientSecret"]));

builder.Services.AddAuthentication(o =>
{
    o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o =>
{
    o.Authority = Issuer;
    o.ClientId = ClientId;
    o.ClientSecret = builder.Configuration["TenancyEngine:ClientSecret"];   // omit for a public PKCE client
    o.ResponseType = "code";            // PKCE is on by default
    o.SaveTokens = true;                // stores access_token, id_token, refresh_token and expires_at in the cookie session
    o.GetClaimsFromUserInfoEndpoint = false;
    o.Scope.Clear();                    // the handler adds openid and profile; a resource-bound request may carry neither profile nor email
    o.Scope.Add("openid");
    o.Scope.Add("offline_access");      // needed for a refresh token
    o.Scope.Add("myapp.read");          // a resource scope you registered
    o.Events.OnRedirectToIdentityProvider = context =>
    {
        context.ProtocolMessage.Resource = Resource;   // RFC 8707: the audience of the access token
        // A user who belongs to several workspaces of this app: ask for a specific one. The platform honours the hint only for a
        // workspace the signed-in user really belongs to; anything else falls back to the default workspace.
        if (context.Properties.Items.TryGetValue("tenant_id", out var tenantId) && Guid.TryParse(tenantId, out var tenant))
            context.ProtocolMessage.SetParameter("tenant_id", tenant.ToString());
        return Task.CompletedTask;
    };
    o.Events.OnRemoteFailure = context =>
    {
        // The user signed in but has no workspace in this app: the platform answers access_denied. Show onboarding, not an error page.
        context.Response.Redirect(context.Request.Query["error"] == "access_denied" ? "/no-workspace" : "/sign-in-failed");
        context.HandleResponse();
        return Task.CompletedTask;
    };
});

builder.Services.AddAuthorization();
builder.Services.AddTenancyEngineWebAppAuthority(sp => new TenancyEngineWebAppAuthorityOptions
{
    Resource = Resource,
    Issuer = Issuer,
    CredentialProvider = ct => new ValueTask<string?>(introspectionKey),
});

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

// Page navigation: send the user to the platform sign-in, optionally into one workspace of several.
app.MapGet("/sign-in", (string? tenantId) => Results.Challenge(
    new AuthenticationProperties(tenantId is null ? null : new Dictionary<string, string?> { ["tenant_id"] = tenantId }) { RedirectUri = "/" },
    new[] { OpenIdConnectDefaults.AuthenticationScheme }));

app.MapGet("/no-workspace", () => Results.Content("You do not have a workspace in this app yet. Ask an administrator for an invitation, or create your workspace.", "text/plain"));
app.MapGet("/sign-in-failed", () => Results.Content("Sign-in did not complete. Try again.", "text/plain"));

// A sensitive API call made by your front end with fetch/XHR: the answer is a status code the script can act on, never a redirect.
app.MapPost("/api/orders/{id}/approve", async (HttpContext http, TenancyEngineWebAppAuthority authority, WebAppTokenRefresher refresher, CancellationToken ct) =>
{
    var check = new TenancyEngineAuthorityCheckOptions
    {
        RequiredScope = "myapp.read",
        AllowedClientIds = new[] { ClientId },
        BypassCache = true,   // a write: ask the platform every time
    };

    // Reads GetTokenAsync("access_token") from the cookie session. The ID token and the cookie principal's claims are never used.
    var result = await authority.AuthorizeAsync(http, check, CookieAuthenticationDefaults.AuthenticationScheme, ct);
    if (result.Error == TenancyEngineWebAppAuthorityError.TokenExpired)
    {
        var refreshed = await refresher.TryRefreshAsync(http, ct);
        if (refreshed is not null)
            result = await authority.AuthorizeAsync(refreshed.AccessToken, check, ct);   // the cookie is rewritten in this response
    }

    if (!result.Ok)
        return Reject(result.Error!.Value, apiCall: true);

    return Results.Ok(new { tenantId = result.Authority!.TenantId });
});

// A page the browser navigates to: an expired or revoked session goes back through sign-in, which can redirect.
app.MapGet("/orders/{id}", async (HttpContext http, TenancyEngineWebAppAuthority authority, CancellationToken ct) =>
{
    var result = await authority.AuthorizeAsync(http, new TenancyEngineAuthorityCheckOptions { AnyScope = true }, CookieAuthenticationDefaults.AuthenticationScheme, ct);
    return result.Ok ? Results.Ok() : Reject(result.Error!.Value, apiCall: false, returnUrl: http.Request.Path);
});

// Sign-out: ends the cookie session AND the platform session (see "Sign-out and revocation").
app.MapPost("/sign-out", () => Results.SignOut(
    new AuthenticationProperties { RedirectUri = "/" },
    new[] { CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme }));

app.Run();

// 401 for an API call (a challenge would redirect, and a redirect after a POST loses the request body); a challenge for a page.
static IResult Reject(TenancyEngineWebAppAuthorityError error, bool apiCall, string? returnUrl = null) => error switch
{
    TenancyEngineWebAppAuthorityError.InsufficientScope => Results.StatusCode(StatusCodes.Status403Forbidden),
    TenancyEngineWebAppAuthorityError.RateLimited => Results.StatusCode(StatusCodes.Status429TooManyRequests),
    TenancyEngineWebAppAuthorityError.VerifierUnavailable
        or TenancyEngineWebAppAuthorityError.AuthorityUnavailable
        or TenancyEngineWebAppAuthorityError.CallerUnauthorized => Results.StatusCode(StatusCodes.Status503ServiceUnavailable), // CallerUnauthorized is YOUR key: log and alert, never a 401
    _ when apiCall => Results.Unauthorized(),   // TokenExpired (refresh failed), InvalidToken, Inactive, BindingMismatch
    _ => Results.Challenge(
        new AuthenticationProperties { RedirectUri = returnUrl ?? "/" },
        new[] { OpenIdConnectDefaults.AuthenticationScheme }),
};

Refreshing an expired access token ​

TenancyEngineWebAppAuthority never refreshes a token: on TokenExpired your app does. Two facts from the server shape the pattern:

  • The platform gives the refresh token no reuse leeway (Program.cs:762-767): a refresh token that was already redeemed is dead at once. Two requests refreshing with the same token at the same time would leave one of them with invalid_grant. So refresh one caller at a time per session and let every concurrent request carrying the same old cookie share that one result.
  • A cookie session only learns the new tokens when the response that carries them is sent. A second request that arrives with the old cookie still holds the old refresh token. The refresher below therefore keeps the result of a refresh for 30 seconds, keyed by a hash of the token that was redeemed, so those requests reuse it instead of spending a dead token. If your app makes many parallel API calls, keep the tokens on the server instead (CookieAuthenticationOptions.SessionStore) so there is only ever one current token set.

The new tokens are written back with UpdateTokenValue and SignInAsync, which is where SaveTokens stored them in the first place. The refresh does not send a resource; the binding to your resource is kept by the platform, and a different resource would be refused.

csharp
// file: WebAppTokenRefresher.cs
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;

public sealed record WebAppTokenRefresherSettings(string TokenEndpoint, string ClientId, string? ClientSecret);

public sealed record RefreshedTokens(string AccessToken, string? RefreshToken, DateTimeOffset ExpiresAt);

/// <summary>Single-flight refresh of the tokens saved in the cookie session. Register it with AddHttpClient and keep the memory cache.</summary>
public sealed class WebAppTokenRefresher(HttpClient http, IMemoryCache cache, WebAppTokenRefresherSettings settings)
{
    private static readonly object Gate = new();
    private static readonly TimeSpan ShareFor = TimeSpan.FromSeconds(30);

    /// <summary>Returns the new tokens (already written back to the session cookie), or null when the session cannot be refreshed: sign the user in again.</summary>
    public async Task<RefreshedTokens?> TryRefreshAsync(HttpContext context, CancellationToken cancellationToken)
    {
        var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
        var session = await context.AuthenticateAsync(scheme);
        if (!session.Succeeded || session.Principal is null || session.Properties?.GetTokenValue("refresh_token") is not { Length: > 0 } refreshToken)
            return null;

        // One redemption per refresh token; concurrent callers with the same token await the same task.
        var key = "te-refresh:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken)));
        Lazy<Task<RefreshedTokens?>>? flight;
        lock (Gate)
        {
            if (!cache.TryGetValue(key, out flight) || flight is null)
            {
                flight = new Lazy<Task<RefreshedTokens?>>(() => RedeemAsync(refreshToken));
                cache.Set(key, flight, ShareFor);
            }
        }

        var tokens = await flight.Value.WaitAsync(cancellationToken);
        if (tokens is null)
        {
            cache.Remove(key);
            return null;
        }

        session.Properties.UpdateTokenValue("access_token", tokens.AccessToken);
        if (tokens.RefreshToken is not null) session.Properties.UpdateTokenValue("refresh_token", tokens.RefreshToken);
        session.Properties.UpdateTokenValue("expires_at", tokens.ExpiresAt.ToString("o", CultureInfo.InvariantCulture));
        await context.SignInAsync(scheme, session.Principal, session.Properties);
        return tokens;
    }

    private async Task<RefreshedTokens?> RedeemAsync(string refreshToken)
    {
        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var form = new Dictionary<string, string>
        {
            ["grant_type"] = "refresh_token",
            ["refresh_token"] = refreshToken,
            ["client_id"] = settings.ClientId,
        };
        if (!string.IsNullOrEmpty(settings.ClientSecret)) form["client_secret"] = settings.ClientSecret;
        try
        {
            using var response = await http.PostAsync(settings.TokenEndpoint, new FormUrlEncodedContent(form), timeout.Token);
            if (!response.IsSuccessStatusCode) return null;   // invalid_grant: revoked, expired or already used
            using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(timeout.Token));
            var root = json.RootElement;
            if (!root.TryGetProperty("access_token", out var access) || access.GetString() is not { Length: > 0 } accessToken) return null;
            var seconds = root.TryGetProperty("expires_in", out var expires) && expires.TryGetInt32(out var s) ? s : 300;
            var rotated = root.TryGetProperty("refresh_token", out var refresh) ? refresh.GetString() : null;
            return new RefreshedTokens(accessToken, rotated, DateTimeOffset.UtcNow.AddSeconds(seconds));
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
        {
            return null;
        }
    }
}

TokenExpired is the only error worth a refresh. Inactive (revoked, member removed), BindingMismatch and InvalidToken mean sign in again.

Workspaces: several, or none ​

  • A user in several workspaces of your app can choose one at sign-in. Put the workspace id in the challenge properties (/sign-in?tenantId=... above); the sample forwards it as the tenant_id authorize parameter (ProtocolMessage.SetParameter("tenant_id", ...)). The platform reads it in AuthorizationController.cs:153-162 and honours it only when the signed-in user really holds that membership; a stale or foreign value falls back to the default workspace and can never select someone else's. The access token's tenant_id is then that workspace. To switch, challenge again with another id.
  • A user with no workspace in your app cannot get a resource-bound token. The platform refuses the grant with access_denied (ResourceIndicatorService.cs:158), which reaches your OnRemoteFailure as error=access_denied on the callback. Treat that as an onboarding state, not a failure: tell the person they have no workspace yet and offer an invitation request or workspace creation (the /no-workspace page in the sample). Do not retry the sign-in in a loop.

Sign-out and revocation ​

Results.SignOut(..., Cookies, OpenIdConnect) does two things: it removes your cookie session, and it redirects the browser to the platform end-session endpoint (/connect/logout) with the saved ID token as id_token_hint (which is why SaveTokens must be on) and then to your registered post-logout redirect. The platform endpoint ends the platform sign-in session and revokes the user's refresh tokens (AuthorizationController.cs:823-840, BffRefreshTokenRevoker.RevokeUserRefreshTokensAsync), so a refresh token copied out of a stolen cookie stops working. There is no separate token-revocation endpoint to call from your app.

  • Make sign-out a POST with an anti-forgery check (a GET sign-out can be triggered by any page).
  • An access token that was already issued stays signed and unexpired until its exp; it is refused earlier only when the platform's introspection reports it inactive. Sensitive actions should therefore keep BypassCache = true, and your sign-out removes the cookie that held the token.
  • The post-logout redirect must be registered on the OAuth client; an unregistered one is refused and the browser lands on a platform info page.
  • Removing only your own cookie (no redirect through the OpenID Connect scheme) does NOT revoke the refresh token: always sign out through both schemes as above.

What it checks ​

Locally, on the access token only:

CheckRejected as
typ header is at+jwt (an ID token is JWT)wrong_type
Algorithm RS256, signature by a key in the issuer's JWKS selected by kid; unsigned and HMAC tokens refusedbad_signature, unknown_key, wrong_algorithm
iss equals the configured issuerwrong_issuer
Exactly one audience, equal to Resource (ordinal)wrong_audience
exp in the future (30 s skew), nbf not in the futureTokenExpired (expired), not_yet_valid
No cnf claim (sender-constrained tokens cannot be proven from a cookie)sender_constrained
sub, client_id and tenant_id present (no azp substitute)claims_missing
At most 8192 characters, compact JWS shapetoken_malformed

Then TenancyEngineVerifiedClaims are built from that verified token and nothing else, and TenancyEngineCurrentAuthorityChecker.CheckAsync confirms the platform still honours it (not revoked, member still in the workspace) and that its answer matches the verified subject, client, tenant, audience, expiry and scopes.

A key rotation: a token signed by a key the app has not seen refreshes the issuer's key set once (rate limited). As with JwtBearer, the refresh can complete in the background, so the first request after a rotation may fail and the next one succeeds.

Issuer origin, JWKS origin and introspection origin ​

There is one value, Issuer, and everything derives from it:

  • the iss a token must carry (with or without the trailing slash);
  • discovery at {issuer origin}/.well-known/openid-configuration, whose issuer must be the same issuer and whose jwks_uri must be on that origin;
  • the introspection endpoint {issuer origin}/api/v1/runtime/oauth/introspect.

The introspection endpoint is derived from the issuer because the issuer is the origin the platform lane table vouches for (the issuer must pass TenancyEngineIssuerResolver like every SDK issuer: a look-alike of a platform zone is refused, a production deployment refuses a lab issuer), and the API key is only ever sent to that origin. An app whose API lives on another origin than its issuer (for example issuer https://auth.lab.saasruntime.com, platform API https://api.lab.saasruntime.com) needs no override: Resource is the app's own API base URL and is never contacted; Issuer is the platform's authorization server. There is no separate introspection base option on purpose, so there is nothing to set wrongly and no way to point the key somewhere else. Issuer must be an origin (no path, query or fragment), which is what makes "derived from the issuer" and "on the issuer's origin" the same statement.

Both HTTP clients (discovery/JWKS and introspection) are built by the SDK from a SocketsHttpHandler with AllowAutoRedirect = false and UseCookies = false; any 3xx is a failure and the final request URI must be exactly the one asked for. There is no way to supply your own HttpClient.

Operating notes ​

  • One long-lived instance (the DI singleton). It owns the key cache, the introspection cache and both clients.
  • Writes and irreversible actions use BypassCache = true. The introspection cache (default 5 s, at most 15 s) can hide a revocation for its lifetime.
  • The helper never refreshes a token. On TokenExpired, refresh with the saved refresh token (one caller at a time) or challenge the user again.
  • A scope decision is mandatory (RequiredScope, or AnyScope = true on purpose); a call with neither throws ArgumentException before any token work.
  • Local rejections carry a fixed Reason word and are logged at Debug with that word only. The token, the key and bodies are never logged or placed in a result.
  • Metrics for the platform call come from the current-authority checker (meter TenancyEngine.Sdk.CurrentAuthority).

See also: Run your own MCP server (bearer resource servers), App staff authorization, the SDK README section "Web app access-token check".

TenancyEngine platform documentation