skip to content

In ASP.NET Core 10, how do RequireHost and the [Host] attribute restrict which requests an endpoint matches, and why are they not a security boundary?

level: seniorimportance: nice to knowfreq 18%

answer

  1. host, *.wildcard, *:port
  2. any listed host is enough
  3. host-specific endpoint outranks a generic one
  4. Host header comes from the client
  5. AllowedHosts host filtering

basics

~20 s

RequireHost and [Host] add host metadata that routing matches against the request's Host header and port; a non-matching host leaves the endpoint out, usually ending in 404. Clients control the Host header, so it routes traffic but does not authorize it.

solid answer

~40 s

`.RequireHost("admin.example.com")` on a Minimal API, or `[Host("admin.example.com")]` on a controller or action, adds host metadata that routing's host matcher policy checks. A pattern can be a host matching any port, a wildcard like `*.example.com` matching any subdomain but not the bare domain, a port only like `*:5001`, or a host with a port; several patterns mean any of them. Endpoints whose host does not match are dropped, and when the same template exists with and without a host, the host-specific one wins. An action's `[Host]` replaces the controller's. The catch: the `Host` header is sent by the client, so the docs warn it can be spoofed. Use it to route traffic, protect admin endpoints with authorization or a separate listener, and restrict accepted hosts with host filtering (`AllowedHosts`).

code

json · 9 lines
json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "api.example.com;partners.example.com;*.partners.example.com"
}

go deeper

for a junior

Recall that RequireHost and [Host] limit an endpoint to certain host names or ports.

for a middle

Explain the pattern forms, that any listed pattern is enough, and that a non-matching host simply removes the endpoint from matching.

for a senior

Use host matching for multi-tenant or multi-site routing while securing endpoints with authorization, host filtering and port binding, and account for proxies rewriting Host.

for a principal

Decide whether separate hosts deserve separate deployments rather than one app with host-matched endpoints, weighing isolation against operational cost.

## What host matching does Endpoint routing can match on more than the path. **Host matching** lets one ASP.NET Core 10 app serve different endpoints depending on the host name or port in the request. A food-delivery platform might serve the customer API on `api.example.com` and a restaurant dashboard on `partners.example.com` from the same process. ```csharp app.MapGet("/orders/{id:int}", (int id) => $"customer view {id}") .RequireHost("api.example.com"); app.MapGet("/orders/{id:int}", (int id) => $"restaurant view {id}") .RequireHost("partners.example.com", "*.partners.example.com"); ``` For controllers the same metadata comes from `[Host(...)]` on the class or action. If both carry it, the **action's attribute is used** and the controller's is ignored. ## Pattern forms Per the routing docs and the host matcher policy: | Pattern | Matches | |---|---| | `www.example.com` | that host on any port | | `*.example.com` | any subdomain, such as `api.example.com` or `a.b.example.com`, on any port, but not `example.com` itself | | `*:5001` | any host on port 5001 | | `www.example.com:5001` | that host on that port only | Several patterns in one call or attribute are alternatives: the endpoint matches if **any** of them does. Matching is case-insensitive. ## How it interacts with selection - A request whose host matches none of an endpoint's patterns removes that endpoint from the candidates. If nothing else matches, the result is an ordinary **404**, not a 403 or 421. - When two endpoints have the same template and order, the one **with** host metadata is considered more specific than one without, so a generic endpoint can serve every other host while a host-specific endpoint takes over for its host, with no ambiguity. - Two endpoints with the same template and **overlapping** host patterns, such as `*.example.com` and `api.example.com` both matching `api.example.com`, can still tie. ## Why it is not a security boundary The `Host` header, and therefore `HttpRequest.Host`, is supplied by the client. Anyone who can reach the server can send `Host: partners.example.com` to the public IP and reach the restaurant endpoints. The ASP.NET Core docs carry an explicit warning that APIs relying on the Host header, including `RequireHost`, are subject to spoofing, and suggest two mitigations: 1. **Check the port the connection actually arrived on**, `HttpContext.Connection.LocalPort`, when separating admin traffic by port, for example by binding the admin endpoints to a Kestrel port that only the internal network can reach. 2. **Use host filtering**, which rejects requests whose host is not in an allow-list. The templates' `appsettings.json` contains `"AllowedHosts": "*"`; replacing `*` with the real host names makes the default host-filtering middleware reject other hosts with 400. Even with both, the restaurant dashboard still needs **authorization** (`RequireAuthorization` with a partner policy). Host matching decides *which* endpoint answers; it never decides *who* may call it. ## Host matching on controllers ```csharp [ApiController] [Route("orders")] [Host("partners.example.com", "*.partners.example.com")] public class PartnerOrdersController : ControllerBase { [HttpGet("{id:int}")] public IActionResult Get(int id) => Ok(new { id, view = "restaurant" }); [HttpGet("{id:int}/health")] [Host("*:5005")] // replaces the controller's [Host] for this action public IActionResult Health(int id) => Ok(); } ``` The second action shows the override rule: its own `[Host]` replaces the class-level one, so it answers on port 5005 for any host name and no longer on the partner host names. ## Behind a reverse proxy If a proxy or load balancer rewrites the Host header, host matching sees the proxy's value unless the forwarded-headers middleware restores the original. Check what host the app actually receives before relying on host patterns. ## What interviewers listen for - The four pattern forms, and that `*.example.com` excludes the bare domain. - That a non-matching host yields 404 and host-specific endpoints outrank generic ones. - That the Host header is client-controlled: route with it, authorize separately, and filter hosts.

  • One endpoint maps /menu with RequireHost("partners.example.com") and another maps /menu with no host. Which runs for a request to partners.example.com?
    The host-specific one. Both match the path and have the same order and precedence, but routing's host comparer treats an endpoint with host metadata as more specific than one without. Requests for any other host fall through to the generic `/menu` endpoint, so there is no ambiguity.
  • How would you keep an internal admin endpoint off the public internet in an ASP.NET Core app?
    Not with `RequireHost` alone, since the Host header is client-controlled. Bind the admin endpoints to a separate Kestrel port reachable only from the internal network and check `Connection.LocalPort` (or use `RequireHost("*:port")` with that binding), restrict hosts with host filtering, and still require an authorization policy on the endpoints.

  • Uses RequireHost("admin.example.com") as the only protection for admin endpoints.
  • Expects *.example.com to also match the bare example.com.
  • Says a request with a non-matching host gets 403 Forbidden.
  • Thinks several hosts in one RequireHost call must all match.
  • Assumes a controller-level [Host] still applies when the action has its own [Host].