Your ASP.NET Core raw WebSocket endpoint for auction bids trusts the site's auth cookie; why does CORS not protect it, and what does WebSocketOptions.AllowedOrigins enforce?
answer
- browsers send cookies, skip preflight
- cross-site WebSocket hijacking
- empty AllowedOrigins allows every origin
- mismatch answered with 403
- no Origin header passes the check
basics
~20 sBrowsers skip CORS for WebSocket handshakes, so any site can open a socket carrying the user's cookie. With entries, AllowedOrigins makes the middleware answer 403 to unlisted origins; empty (the default) allows all, and requests without Origin pass.
solid answer
~40 sA WebSocket handshake gets no preflight and browsers ignore `Access-Control-*` headers for it, so a CORS policy does nothing. Yet the browser still attaches the user's cookies, so a page on any site could open a bidding socket as the logged-in user: cross-site WebSocket hijacking. What the browser does send is an `Origin` header, and `WebSocketOptions.AllowedOrigins` checks it. It is empty by default, which allows every origin, as does a `"*"` entry. With entries, `WebSocketMiddleware` answers a WebSocket request whose `Origin` is not listed with 403 before your endpoint runs. Requests with no `Origin` pass, because non-browser clients do not send one, so it is a browser defence, not authentication: keep `RequireAuthorization()` on the endpoint and check what the user may do on each message.
code
csharp · 13 linesvar webSocketOptions = new WebSocketOptions
{
AllowedOrigins = { "https://bids.example.com", "https://admin.bids.example.com" }
};
app.UseWebSockets(webSocketOptions); // other origins get 403 before the endpoint runs
app.Map("/bids", async (HttpContext context, AuctionFeed auctions) =>
{
if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = 400; return; }
using var socket = await context.WebSockets.AcceptWebSocketAsync();
await auctions.ServeBidderAsync(socket, context.User, context.RequestAborted);
})
.RequireAuthorization(); // anonymous handshakes are refused before acceptgo deeper
Remember that CORS does not apply to WebSocket handshakes and that AllowedOrigins is empty, meaning allow-all, by default.
Explain how WebSocketMiddleware uses the Origin header: listed origins pass, others get 403, and header-less requests pass.
Describe cross-site WebSocket hijacking with cookie auth and layer AllowedOrigins, RequireAuthorization and per-message authorisation into one design.
Weigh cookie-based socket auth against explicit tokens for cross-site clients and decide what a long-lived socket must re-check as permissions change.
## The attack: cross-site WebSocket hijacking Picture an auction site where a signed-in bidder's browser holds an authentication cookie for `bids.example.com`. The raw WebSocket endpoint `/bids` accepts the socket if the user is authenticated, then lets them place bids. Now the bidder visits an unrelated, malicious page. Its script runs `new WebSocket("wss://bids.example.com/bids")`. The browser: - **does not send a CORS preflight** for a WebSocket handshake; - **does not enforce `Access-Control-Allow-Origin`** on the response; - **does attach the cookies** for `bids.example.com`. So the server sees an authenticated request and accepts it, and the malicious page can now read the bid stream and send bids as the victim. This is **cross-site WebSocket hijacking (CSWSH)**. Because the browser never consults CORS for this handshake, `AddCors`, `UseCors` and `RequireCors` on the endpoint do not help. ## The defence ASP.NET Core gives you: AllowedOrigins The one thing a browser reliably includes is the **`Origin` header** naming the page's origin. `WebSocketOptions.AllowedOrigins` (an `IList<string>`) tells `WebSocketMiddleware` which values to accept: | Configuration | Behaviour | |---|---| | list empty (the default) | every origin is allowed | | list contains `"*"` | every origin is allowed | | list has entries | a WebSocket request whose `Origin` is not in the list gets **403 Forbidden** | | request has no `Origin` header | allowed, whatever the list says | Details from the middleware source worth knowing: - The check runs **in the middleware**, before routing reaches your endpoint, and only for requests that are WebSocket requests. - The list values are lower-cased once and compared exactly to the header, so write entries as full origins: scheme, host and non-default port, for example `https://bids.example.com`, with no trailing slash or path. - Nothing is logged above `Debug` when a request is refused, so a mis-typed origin shows up as unexplained 403s. ## Keeping the list in configuration Origins differ per environment (localhost in development, a staging host, the production domain), so hard-coding them invites drift. `AddWebSockets` configures the same options from code that can read configuration: ```csharp builder.Services.AddWebSockets(options => { foreach (var origin in builder.Configuration.GetSection("Bids:AllowedOrigins").Get<string[]>() ?? []) options.AllowedOrigins.Add(origin); }); // later: app.UseWebSockets(); picks up the configured WebSocketOptions ``` Use the parameterless `UseWebSockets()` here: the overload that takes a `WebSocketOptions` instance wraps that instance with `Options.Create` and ignores what `AddWebSockets` configured. Leaving the section empty in an environment silently means allow-all, so treat a missing value as a deployment error and fail fast if the list is empty in production. ## Why it is not authentication `Origin` is set by browsers, which a malicious *page* cannot forge. But any non-browser client (a script, a bot, `curl`) can send any `Origin` or none at all. The middleware lets header-less requests through on purpose so that server-to-server clients still work. So: 1. Use `AllowedOrigins` to stop **browsers** on other sites from riding the user's cookie. 2. Still authenticate the handshake: put `.RequireAuthorization()` on the mapped endpoint, so `UseAuthorization` rejects anonymous handshakes before the socket is accepted. 3. Authorise **each message**, not only the handshake: a socket can live for hours, through role changes and logouts. 4. Consider a short-lived token in the query string or the first message instead of cookies for cross-site clients; it is not sent automatically, which removes the hijacking vector. ## A common misreading "Our CORS policy only allows our front end, so the socket is safe" is the misconception interviewers are fishing for. CORS restricts what a browser lets a page *read* from ordinary fetches; WebSocket handshakes are outside it entirely. The allow-list on `WebSocketOptions` is the ASP.NET Core control built for this gap.
- Why does the middleware let a request with no Origin header through when AllowedOrigins is set?Browsers always send `Origin` on a WebSocket handshake, but server-side and native clients usually do not. Rejecting header-less requests would break those clients while adding no protection, since such a client could just as easily send an allowed value. The allow-list exists to stop *browsers* on other sites from using the victim's cookies; non-browser callers must be stopped by authentication.
- Would SameSite cookies remove the need for AllowedOrigins?They reduce it: a `SameSite=Lax` or `Strict` cookie is not attached to requests initiated from another *site*, which covers many hijacking attempts. But a different origin on the same site (another subdomain) still gets the cookie, and cookie settings are easy to loosen later. Keeping an explicit `AllowedOrigins` list is cheap defence in depth.
- A CORS policy with UseCors stops other sites from opening our WebSocket.
- AllowedOrigins defaults to the app's own origin.
- AllowedOrigins authenticates clients, so the endpoint needs no RequireAuthorization.
- Requests without an Origin header are rejected once AllowedOrigins has entries.
- Checking the user once at the handshake is enough for an hours-long socket.