ASP.NET Core bridge
StellaOps.Microservice.AspNetCore publishes the endpoints of an existing ASP.NET Core application (minimal APIs or controllers) to a Router gateway, without rewriting them as endpoint classes. The gateway routes requests to the application over a transport, and the bridge runs the matched ASP.NET Core endpoint.
The code on this page is compiled and run before each release; the scenario An existing ASP.NET Core API behind the gateway shows a complete application. Read What the endpoint sees of the caller before you rely on
HttpContext.User.
When to use it
| Situation | Use |
|---|---|
| An ASP.NET Core API that must stay one, served directly and through the gateway | The bridge |
| A new service | Endpoint classes: compile-time discovery, no ASP.NET Core runtime |
| A service that must read the caller’s identity | The bridge, with the gateway’s identity envelope key (below) |
Packages
<PackageReference Include="StellaOps.Microservice.AspNetCore" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Router.Transport.Tcp" Version="$(RouterPackageVersion)" />
The bridge brings StellaOps.Microservice as a dependency. The project uses the Web SDK (Microsoft.NET.Sdk.Web), so the generic host is already there.
Publish the application
Register the bridge with the gateway address, and the transport client:
// Publish the minimal API endpoints below to the gateway as the service "orders". The bridge // routes the gateway's requests to the ASP.NET Core endpoints they match. builder.Services.AddStellaRouterBridge(options => { options.ServiceName = "orders"; options.Version = "1.0.0"; options.Region = "demo"; options.InstanceId = builder.Configuration["Router:InstanceId"]; options.Routers = [ new RouterEndpointConfig { Host = gatewayHost, Port = gatewayPort, TransportType = TransportType.Tcp } ]; }); // Keep the heartbeat below the gateway's degraded threshold. builder.Services.Configure<StellaMicroserviceOptions>(options => options.HeartbeatInterval = TimeSpan.FromSeconds(10)); builder.Services.AddTcpTransportClient(options => { options.Host = gatewayHost; options.Port = gatewayPort; });Declare authorization on every endpoint. The bridge turns it into the claims the gateway checks:
// Authorization metadata becomes the claims the gateway checks: a policy that requires the scope // claim orders:read is published as the claim requirement scope=orders:read. builder.Services.AddAuthorizationBuilder() .AddPolicy("orders:read", policy => policy.RequireClaim("scope", "orders:read")) .AddPolicy("orders:write", policy => policy.RequireClaim("scope", "orders:write"));app.MapPost("/orders", (CreateOrder request) => { var order = new Order($"ORD-{orders.Count + 1:D4}", request.CustomerId, request.Total, "open"); orders[order.Id] = order; return Results.Created($"/orders/{order.Id}", order); }) .RequireAuthorization("orders:write"); app.MapGet("/orders/{id}", (string id) => orders.TryGetValue(id, out var order) ? Results.Ok(order) : Results.NotFound()) .RequireAuthorization("orders:read");Add routing and the bridge before the endpoints:
app.UseRouting(); app.UseStellaRouterBridge(); ...the Map calls...The bridge reads the endpoints once the host has started, so every endpoint mapped before
app.Runis published.Run the gateway, then the application with
STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS=truefor TCP. Call it through the gateway:curl -i -X POST http://localhost:5080/orders \ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"customerId":"CUST-001","total":42.5}'Expected result:
201and the orderORD-0001with a token that carriesorders:write;403without that scope;401without a token.
How authorization maps to claims
AuthorizationMapping selects the source of each endpoint’s claims:
| Value | Claims come from |
|---|---|
Hybrid (default) | ASP.NET Core authorization metadata, and microservice.yaml overrides where an entry exists |
AspNetMetadataOnly | ASP.NET Core authorization metadata only |
YamlOnly | microservice.yaml only (YamlConfigPath) |
A policy built with RequireClaim(type, values) becomes a requirement of that claim; a scope policy becomes scope with its value. OnMissingAuthorization decides what happens to an endpoint without [Authorize], [AllowAnonymous] or RequireAuthorization:
| Value | Effect |
|---|---|
RequireExplicit (default) | The application stops at start-up and names the endpoint: Endpoint <METHOD> <path> has no authorization metadata. Add RequireAuthorization or [Authorize] ... |
WarnAndAllow | The endpoint is published; it requires an authenticated caller and no claim. A warning is logged. |
AllowAuthenticated | As WarnAndAllow, without the warning. |
Policies the bridge translates into gateway claims:
| Policy content | Gateway requirement |
|---|---|
RequireAuthenticatedUser() | An authenticated caller, no claim |
RequireClaim(type), RequireClaim(type, values) | That claim, with one of the values when given |
RequireRole(roles) | The role claim with one of the roles |
RequireUserName(name) | The name claim with that value |
A custom requirement with a RequiredScopes, Scopes or AllowedScopes property (and RequireAllScopes) | The scope claim with those values, any one or all |
Any other requirement, such as RequireAssertion, cannot be translated. The application logs a warning at start-up for each such policy, and the gateway answers 403 for its endpoints, because it cannot check what the policy asks for. Replace such a requirement with one of the forms above.
The gateway requires an authenticated caller for every published endpoint except one with [AllowAnonymous] (or AllowAnonymous()): such an endpoint is public through the gateway, which checks neither a token nor claims for it.
Options
AddStellaRouterBridge takes StellaRouterBridgeOptions, set in code:
| Option | Default | Meaning |
|---|---|---|
ServiceName, Version, Region | none, required | As for an endpoint-class service (Microservice SDK). |
InstanceId | <ServiceName>-<GUID>, the GUID as 32 hexadecimal digits | The instance identifier. Each process needs its own (Microservice SDK: options). |
ServiceDescription | none | Text for the gateway’s OpenAPI document. |
AuthorizationMapping | Hybrid | See above. |
YamlConfigPath | none | A microservice.yaml with overrides. |
OnMissingAuthorization | RequireExplicit | See above. |
OnUnsupportedConstraint | WarnAndStrip | A route constraint the gateway cannot match, such as {id:int}: WarnAndStrip publishes the path without it and logs a warning, SilentStrip does the same without the warning, Fail stops the application at start-up. The application still enforces the constraint when it runs the endpoint. |
EndpointFilter | none | A function that returns false for an endpoint to keep it off the gateway. |
ExcludedPathPrefixes | /health, /healthz, /readyz, /livez, /metrics, /swagger, /openapi, /.well-known/openapi, /api/v1/buildinfo, /catalog-changes | Paths that stay local to the application. |
IncludeExcludedPathsInRouter | false | Publish the excluded paths too. |
DefaultTimeout | 30 seconds | The timeout of endpoints that set none. Above 0 and at most 10 minutes. Every bridged endpoint carries a timeout, so the gateway’s own Gateway:Routing:DefaultTimeout does not apply. |
EnableStreaming | false | Mark endpoints that return a streaming response as streaming endpoints. The bodies are still held in memory in this release (File uploads and downloads). |
ExtractSchemas, ExtractOpenApiMetadata | true | Publish request and response schemas and OpenAPI metadata. |
AuthorizationTrustMode | Hybrid | How the endpoint’s caller identity is built (below). |
IdentityEnvelopeSigningKey | none | The key that verifies the gateway’s identity envelope, the same as the gateway’s Gateway:IdentityEnvelope:SigningKey (below). |
IdentityEnvelopeClockSkew | 30 seconds | The clock difference allowed when the bridge checks the envelope’s timestamps. |
Routers (the gateways to connect to) is set on the bridge options, as in step 1; the other microservice options (HeartbeatInterval and the rest) are set with Configure<StellaMicroserviceOptions>. RefreshStellaRouterEndpoints() clears the bridge’s endpoint cache; the next discovery reads the endpoints again.
What the endpoint sees of the caller
A bridged request does not run the application’s middleware: the bridge matches the endpoint and runs it directly. So the application’s own authentication does not run, and the bridge sets HttpContext.User from the identity envelope the gateway signs for an authenticated caller. The gateway removes every identity header a caller sends (X-StellaOps-Actor, X-StellaOps-Scopes and the others listed in Router gateway host), and the bridge never reads the caller’s identity from request headers.
Give the gateway and the application the same random key of at least 32 characters, from configuration or the environment and never from source control:
- the gateway:
Gateway:IdentityEnvelope:SigningKey(environmentGateway__IdentityEnvelope__SigningKey); - the application:
IdentityEnvelopeSigningKeyinAddStellaRouterBridge.
A verified envelope becomes a principal of authentication type StellaRouterEnvelope with sub, one scope claim per scope, role claims, stellaops:tenant and stellaops:project when the token carries them, and the claims iss, client_id, name, preferred_username and email. AuthorizationTrustMode decides what happens without one:
AuthorizationTrustMode | Valid envelope | No envelope, or one that does not verify |
|---|---|---|
Hybrid (default) | Sets HttpContext.User | HttpContext.User carries no identity; an envelope that does not verify is logged |
GatewayEnforced | Sets HttpContext.User | 403 before the endpoint runs |
ServiceEnforced | Ignored | HttpContext.User carries no identity |
Without the key on either side, HttpContext.User carries no identity whatever the bearer token says. The gateway’s own check does not depend on the key: it checks the endpoint’s published claims against the bearer token, and refuses the request with 401 or 403 before it reaches the application.
Cancellation and errors
HttpContext.RequestAborted of a bridged request is the Router request’s token: a gateway timeout or a caller disconnect cancels it. Pass it to every await. A cancelled request returns no answer of its own; the gateway has already answered the caller.
When the bridge itself cannot answer, the caller gets a problem-details body:
| Case | Status | Detail |
|---|---|---|
| No endpoint of the application matches the request | 404 | No endpoint matched the request. |
The endpoint throws NotImplementedException | 501 | An internal error occurred. |
| The endpoint throws any other exception | 500 | An internal error occurred. (the exception type is logged; its message is not sent) |
AuthorizationTrustMode is GatewayEnforced and no valid envelope arrived | 403 | Gateway identity envelope verification failed. |
WebSocket endpoints and other connection upgrades are not carried through the gateway: the bridge forwards request and response bodies only.
Pitfalls
- The application stops at start-up with
Stella microservice options validation failed.A required option is missing:ServiceName, a semanticVersion,Region, or aRoutersentry inAddStellaRouterBridge. The message does not say which. - The application stops at start-up and names an endpoint without authorization metadata. With the default
OnMissingAuthorization(RequireExplicit), every published endpoint needs an authorization requirement or anonymous access. AddRequireAuthorization(or[Authorize]) to that endpoint, or setOnMissingAuthorizationtoWarnAndAlloworAllowAuthenticated. Add[AllowAnonymous]only to an endpoint that is meant to be public: through the gateway it then needs no token at all. - A request to a health or OpenAPI path returns
404through the gateway. It is inExcludedPathPrefixesand stays local.
