Upgrade to 4.0Changelog
Guides

Bind a host context to an OAuth grant

Keep an OAuth client in the organization, workspace, or region the person chose at consent, and check it again at every refresh.

Many apps have a host context: an organization, workspace, tenant, or region. The person picks one in the UI, and the app keeps it as their current context. When that person connects an OAuth client, such as an AI assistant, the client should work in the context the person chose at consent, and stay there.

Do not read the person's stored current context on calls made with a token. If you do, switching context in the browser silently moves every connected client too. Bind the context to the grant instead:

  1. The consent page asks which organization to connect.
  2. Your approve endpoint checks membership and puts the organization on the token as a claim.
  3. Your API reads the claim, not the person's current organization.
  4. A validator checks the membership again at every refresh, and ends the grant when it is gone.

It uses the AuthEndpoints.OpenIddict package (preview). The examples say "organization"; the same steps work for a workspace, a tenant, or a region.

1. Approve with the chosen organization

Turn off the built-in approve route, or leave it for clients that need no organization, and map your own. The consent page still reads the card from GET /oauth/requests/{id}, then posts the person's choice here:

public sealed record ApproveForOrganization(string? OrganizationId);

app.MapPost("/account/oauth/requests/{id:guid}/approve", async (
        Guid id, ApproveForOrganization body, HttpContext http, IOAuthConsentService consent, OrganizationMembers members) =>
    {
        var userId = http.User.FindFirstValue(ClaimTypes.NameIdentifier)!;
        if (string.IsNullOrEmpty(body.OrganizationId) || !await members.IsMemberAsync(userId, body.OrganizationId))
        {
            return Results.Problem(statusCode: StatusCodes.Status403Forbidden, title: "Not a member of this organization");
        }

        var result = await consent.ApproveAsync(id, userId, context =>
        {
            var principal = OAuthPrincipals.ForSubject(context.UserId);
            principal.SetClaim(OrganizationGrantValidator.OrganizationClaim, body.OrganizationId);
            foreach (var claim in principal.FindAll(OrganizationGrantValidator.OrganizationClaim))
            {
                claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken);
            }

            return ValueTask.FromResult<ClaimsPrincipal?>(principal);
        });

        return result.Status == OAuthConsentStatus.Approved
            ? Results.Ok(new { redirectUrl = result.RedirectUrl })
            : Results.NotFound();
    })
    .RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = IdentityConstants.ApplicationScheme })
    .RequireAntiforgery(allowBearer: false);
  • The membership check runs before anything is consumed. A refused request stays open, so the person can pick another organization.
  • sub stays the person's user id, so AccessTokenClaims.Roles and AccessTokenClaims.UserId still work.
  • The org_id claim is stored in the code and the refresh token. Every access token issued from this grant carries the same value. Nothing is written to the person's record.
  • If the organization decides who the token acts as (a service account per organization), return that subject from the callback instead. See Who is the token subject.

2. Read it in the API

app.MapGet("/api/reports", (ClaimsPrincipal user, ReportStore reports) =>
{
    var organization = user.FindFirst("org_id")?.Value; // from the token, never from the user's current organization
    return organization is null ? Results.Forbid() : Results.Ok(reports.For(organization));
}).RequireAuthorization("api");

On routes that cookie users share, use the claim when User.IsOAuthDelegated() is true, and the person's current organization otherwise.

3. Check it again at every refresh

The server already checks the person at every code exchange and refresh (RevalidateUser, on by default) through IOAuthUserValidator. Its ValidateAsync method gets an OAuthUserValidationContext with the grant's own claims in Grant, so it can read the organization the approve endpoint bound. Wrap the default validator and check membership too:

public sealed class OrganizationGrantValidator(
    IdentityOAuthUserValidator<AppUser> identity,
    OrganizationMembers members) : IOAuthUserValidator
{
    public const string OrganizationClaim = "org_id";

    public ValueTask<string?> GetStampAsync(string userId, CancellationToken cancellationToken)
        => identity.GetStampAsync(userId, cancellationToken);

    public ValueTask<bool> IsValidAsync(string userId, string? stamp, CancellationToken cancellationToken)
        => identity.IsValidAsync(userId, stamp, cancellationToken);

    // Runs at every code exchange and refresh.
    public async ValueTask<bool> ValidateAsync(OAuthUserValidationContext context, CancellationToken cancellationToken)
    {
        if (!await identity.IsValidAsync(context.UserId, context.SecurityStamp, cancellationToken))
        {
            return false;
        }

        // Grants approved without an organization (the built-in consent API) have no claim to check.
        return context.Grant.FindFirst(OrganizationClaim)?.Value is not { } organization
            || await members.IsMemberAsync(context.UserId, organization, cancellationToken);
    }
}

Register it after AddOAuthServer, which registers the default with TryAdd:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options => { /* … */ });
builder.Services.AddScoped<IdentityOAuthUserValidator<AppUser>>();
builder.Services.Replace(ServiceDescriptor.Scoped<IOAuthUserValidator, OrganizationGrantValidator>());
  • The Identity checks still apply: a changed password or security stamp, a lockout, or a deleted account ends the grant.
  • When the person leaves the organization, the next refresh gets invalid_grant and the grant and its tokens are revoked. An access token that was already issued works until it expires (AccessTokenLifetime, 15 minutes by default). To cut it off at once, revoke the grant when you remove the membership, with IOAuthConsentService.RevokeAuthorizationAsync.
  • context.Grant holds the claims of the code or refresh token: sub and what your callback added. The package's internal claims (the approving user id and stamp) and OpenIddict's oi_* claims are removed. Use context.UserId, context.SecurityStamp, context.Scopes, context.ClientId, and context.AuthorizationId for those.
  • ValidateAsync has a default that calls IsValidAsync(userId, stamp), so validators written before it existed keep working unchanged.

Earlier versions of this guide carried the organization inside the stored stamp (GetStampAsync returned organization|stamp, read from HttpContext.Items), because the validator could not see the grant. That still works, but read context.Grant instead: it keeps app data out of a security value.

Checklist

  • The consent page asks for the organization and posts it to your approve endpoint.
  • The approve endpoint checks membership before ApproveAsync, and puts the organization on the token.
  • APIs called with tokens read the claim, not the person's current organization.
  • OrganizationGrantValidator replaces IOAuthUserValidator, so removing a membership ends the grant at its next refresh.

The package's tests run this guide's code: OAuthGrantContextRecipeTests in the repository.