skip to content

A SignalR hub on api.example.com serves a browser app on app.example.com. Which CORS policy does the hub need, and why can it not use AllowAnyOrigin?

level: seniorimportance: should knowfreq 40%

answer

  1. withCredentials defaults to true
  2. WithOrigins plus AllowCredentials
  3. custom headers force a preflight
  4. GET, POST and DELETE
  5. CORS does not cover the WebSocket

basics

~20 s

The SignalR JavaScript client sends credentials by default, so the hub needs a policy with WithOrigins for the app's origin, AllowCredentials, its request headers and GET, POST and DELETE. ASP.NET Core refuses to build a policy combining AllowAnyOrigin with AllowCredentials.

solid answer

~40 s

The JavaScript client's `withCredentials` option defaults to `true`, so negotiate, long-polling and Server-Sent Events requests are credentialed; that keeps cookie authentication and cookie-based affinity working, and the docs require it even when the app does not authenticate. A credentialed response must name the exact origin, so the policy is `WithOrigins("https://app.example.com")` plus `AllowCredentials()`. The client adds `X-Requested-With` and `X-SignalR-User-Agent`, and often `Authorization`, so requests are preflighted and the policy needs `AllowAnyHeader()` or those headers listed, plus `WithMethods("GET", "POST", "DELETE")`, since long polling sends `DELETE` on stop. `AllowAnyOrigin().AllowCredentials()` makes `CorsPolicyBuilder.Build()` throw. Apply the policy with `RequireCors` on `MapHub`, or `[EnableCors]` on the hub, with `UseCors()` in the pipeline. CORS does not protect the WebSocket itself; restrict its origins with `WebSocketOptions.AllowedOrigins`.

code

csharp · 15 lines
csharp
builder.Services.AddCors(options =>
{
    options.AddPolicy("quotes-app", policy => policy
        .WithOrigins("https://app.example.com")
        .AllowAnyHeader()
        .WithMethods("GET", "POST", "DELETE")
        .AllowCredentials());
});

// CORS does not cover the WebSocket upgrade; restrict its Origin separately.
builder.Services.Configure<WebSocketOptions>(o => o.AllowedOrigins.Add("https://app.example.com"));

var app = builder.Build();
app.UseCors();
app.MapHub<QuotesHub>("/hubs/quotes").RequireCors("quotes-app");

go deeper

for a junior

Recall that a browser app on another origin needs a CORS policy on the hub, naming that origin and allowing credentials.

for a middle

Explain why the client is credentialed by default, which headers and methods it sends, and how RequireCors or [EnableCors] attach the policy to the hub's endpoints.

for a senior

Explain why AllowAnyOrigin and reflected origins are unsafe with credentials, and close the WebSocket gap with an origin allow-list because CORS never covers the upgrade.

for a principal

Decide whether the hub should be cross-origin at all, or sit behind the app's own origin, weighing CORS and origin management against deployment topology.

## Why the client makes credentialed requests Cross-origin browser requests carry cookies only in **credentialed** mode. The SignalR JavaScript client sets `withCredentials: true` unless told otherwise, for two reasons the docs give: - **cookie authentication** has to reach the hub; - **cookie-based sticky sessions**, such as the ARR affinity cookie on Azure App Service, must come back on every request of a connection. The docs therefore say credentials must be allowed even when the app does not authenticate. The client option `withCredentials: false` exists for apps that are certain they need no cookies at all. ## The policy SignalR needs | Requirement | `CorsPolicyBuilder` call | Why | |---|---|---| | Name the browser app's origin | `WithOrigins("https://app.example.com")` | credentialed responses must echo an exact origin | | Allow credentials | `AllowCredentials()` | the client sends cookies by default | | Allow the client's headers | `AllowAnyHeader()` or `WithHeaders(...)` | `X-Requested-With`, `X-SignalR-User-Agent` and `Authorization` trigger a preflight | | Allow the methods | `WithMethods("GET", "POST", "DELETE")` | negotiate and sends use `POST`, polls use `GET`, long polling sends `DELETE` on stop | The client must also use an **absolute URL**, `withUrl("https://api.example.com/hubs/quotes")`, because a relative one would point at the app's own origin. ## Why AllowAnyOrigin cannot work The CORS protocol forbids answering a credentialed request with a wildcard origin. ASP.NET Core enforces that when the policy is built: - `CorsPolicyBuilder.Build()` throws `InvalidOperationException` when `AllowAnyOrigin()` and `AllowCredentials()` are combined, with the message "The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time." - The tempting workaround, `SetIsOriginAllowed(_ => true)` with `AllowCredentials()`, builds without error but reflects any origin back with credentials allowed. Any site a signed-in user visits could then call the hub with their cookies, so it is just as unsafe. List the origins you trust, from configuration if they vary by environment. ## Applying it to the hub 1. Register the named policy with `AddCors`. 2. Add `app.UseCors()` to the pipeline. 3. Attach the policy with `app.MapHub<QuotesHub>("/hubs/quotes").RequireCors("quotes-app")`, or put `[EnableCors("quotes-app")]` on the hub class; `MapHub` copies class attributes onto the hub's endpoints. With only `/negotiate` covered, the browser would still block the transport requests, which is why the policy goes on the hub mapping rather than on one URL. ## Reading the symptoms - **Negotiate blocked, error about credentials.** The policy lacks `AllowCredentials()`, or the response carried a wildcard origin. - **Preflight fails on negotiate.** The client's custom headers are not allowed; add `AllowAnyHeader()` or list them. - **Connected, but stopping a long-polling connection fails.** `DELETE` is missing from the methods. - **Works on the app's own origin only.** The client uses a relative URL, or the policy is not attached to the hub endpoints. ## What CORS does not cover Browsers do not apply CORS to the WebSocket upgrade: a page on any origin can open a WebSocket to the hub, and cookies go with it. The docs point to WebSocket origin restriction instead. Each SignalR hub endpoint runs the WebSockets middleware with the options registered in DI, so configuring `Microsoft.AspNetCore.Builder.WebSocketOptions.AllowedOrigins` with `https://app.example.com` makes upgrades from other origins fail with `403`. Bearer tokens are not attached by the browser on their own, so a token-authenticated hub is less exposed than a cookie-authenticated one.

  • When is it safe to set withCredentials: false on the SignalR JavaScript client?
    Only when nothing on the connection depends on cookies: no cookie authentication, and no load balancer that pins clients with an affinity cookie. Then the policy can drop `AllowCredentials()`. With a bearer token supplied by `accessTokenFactory` and no affinity cookie, that can hold; otherwise connections break in ways that are hard to trace.
  • Why does the hub's CORS policy need DELETE?
    When a long-polling connection stops, the JavaScript client sends a `DELETE` to the hub URL so the server can clean up the connection. Without `DELETE` in the policy, the browser blocks that request, so a cross-origin long-polling client cannot end its connection cleanly.

  • AllowAnyOrigin with AllowCredentials is fine for a hub as long as it uses HTTPS.
  • SetIsOriginAllowed(_ => true) is a safe way around the wildcard restriction.
  • A CORS policy also stops other sites from opening a WebSocket to the hub.
  • CORS credentials are only needed when the hub uses cookie authentication.
  • Applying the policy to the negotiate URL alone is enough for every transport.