Scenario: an existing ASP.NET Core API behind the gateway

Contoso has an orders API built with ASP.NET Core minimal APIs. It wants to serve it through the Router gateway next to new services, without rewriting the endpoints. The ASP.NET Core bridge publishes the existing endpoints to the gateway, and the API keeps serving its own port as before.

The worked example is an orders API; its complete Program.cs closes the steps below. Before each release, an automated run creates and reads an order through the gateway and checks the claims (201, 200, 403).

Before and after

BeforeAfter
Callers reach the APIOn its own addressOn the gateway’s address; the API’s own address can stay internal
AuthorizationASP.NET Core policiesThe same policies, published as endpoint claims and enforced by the gateway
DeploymentBehind a load balancerAny number of instances connect to the gateway; no load balancer entry

Steps

  1. Add the packages to the API project:

    <PackageReference Include="StellaOps.Microservice.AspNetCore" Version="$(RouterPackageVersion)" />
    <PackageReference Include="StellaOps.Router.Transport.Tcp" Version="$(RouterPackageVersion)" />
    
  2. Register the bridge. Name the service and its gateway address, and add the transport client. The bridge hands the gateway’s requests to the ASP.NET Core endpoints:

    // 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;
    });
    
  3. Keep the authorization policies. Each policy that requires a claim becomes a claim 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"));
    
  4. Keep the endpoints, each with its authorization:

    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");
    
  5. Run and call it. Start the gateway, then the API with STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS=true (TCP). The API’s log shows Connected to router at 127.0.0.1:9100, registered 2 endpoints.

    curl -i -X POST http://localhost:5080/orders \
      -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
      -d '{"customerId":"CUST-001","total":42.5}'
    curl -i http://localhost:5080/orders/ORD-0001 -H "Authorization: Bearer $TOKEN"
    

    Expected result: 201 with the order ORD-0001 for a token with orders:write; 200 for a token with orders:read; 403 for a token without the scope.

The complete Program.cs

using System.Collections.Concurrent;
using StellaOps.Microservice;
using StellaOps.Microservice.AspNetCore;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Transport.Tcp;

var builder = WebApplication.CreateBuilder(args);

// The gateway to connect to: Router:Host and Router:Port (environment Router__Host, Router__Port).
var gatewayHost = builder.Configuration["Router:Host"] ?? "127.0.0.1";
var gatewayPort = builder.Configuration.GetValue("Router:Port", 9100);

// 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;
});

// 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"));

var app = builder.Build();

app.UseRouting();
app.UseStellaRouterBridge();

var orders = new ConcurrentDictionary<string, Order>();

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");

await app.RunAsync();

/// <summary>The body of a create request.</summary>
public sealed record CreateOrder(string CustomerId, decimal Total);

/// <summary>An order.</summary>
public sealed record Order(string Id, string CustomerId, decimal Total, string Status);

Moving callers over

  1. Run the API with the bridge while callers still use its own address.
  2. Point callers at the gateway, one at a time. Both paths serve the same endpoints.
  3. When no caller uses the API’s own address, restrict it to the internal network.

Limits