skip to content

How does a browser SignalR client send a bearer token to an ASP.NET Core hub, and why must the server read access_token from the query string?

level: middleimportance: must knowfreq 60%

answer

  1. accessTokenFactory / AccessTokenProvider
  2. Authorization header where the API allows it
  3. browser WebSocket and EventSource: no custom headers
  4. ?access_token= on the hub URL
  5. JwtBearerEvents.OnMessageReceived sets context.Token

basics

~20 s

The client supplies the token through accessTokenFactory. SignalR sends it in an Authorization header where it can, but browsers cannot set headers on WebSocket or EventSource requests, so it appends access_token to the URL; JwtBearer's OnMessageReceived must copy that value into context.Token for hub paths.

solid answer

~40 s

In the JavaScript client, `withUrl(url, { accessTokenFactory: () => getToken() })` provides the token; the .NET client's equivalent is `AccessTokenProvider`. Negotiate, long-polling requests and Server-Sent Events sends go out with `Authorization: Bearer ...`. The browser `WebSocket` and `EventSource` APIs cannot set request headers, so for those two transports the client appends `access_token=...` to the URL. The JWT bearer handler reads only the header by default, so in `AddJwtBearer` you set `JwtBearerEvents.OnMessageReceived`: when the path starts with the hub's path and `access_token` is present, assign it to `context.Token`. Scope it to hub paths so ordinary APIs keep ignoring query-string tokens. Two consequences follow: the hosting `Request starting` log at Information level records the full URL, token included; and the token is validated when the connection is established, not again for the life of the connection.

code

csharp · 19 lines
csharp
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Auth:Authority"];
        options.Audience = "quotes-api";
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                var accessToken = context.Request.Query["access_token"];
                if (!string.IsNullOrEmpty(accessToken) &&
                    context.HttpContext.Request.Path.StartsWithSegments("/hubs/quotes"))
                {
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    });

go deeper

for a junior

Recall that the client gets its token from accessTokenFactory and that, in browsers, WebSockets and Server-Sent Events send it as access_token in the URL.

for a middle

Explain which requests carry a header and which carry the query value, and write OnMessageReceived so it sets context.Token only for hub paths.

for a senior

Cover the operational side: tokens in hosting logs, short lifetimes because a connection keeps its principal, and CloseOnAuthenticationExpiration with its missed-message cost.

for a principal

Choose the token strategy for long-lived connections, weighing short-lived tokens and forced reconnects against session continuity and what your logs may legally retain.

## Where the token comes from SignalR clients never build the `Authorization` header themselves; they ask the app for a token: - JavaScript: `withUrl(url, { accessTokenFactory: () => ... })`, returning a string or a promise of one. - .NET: `WithUrl(url, o => o.AccessTokenProvider = () => Task.FromResult<string?>(token))`. The docs say the factory is called before every HTTP request. The pinned client source is narrower: both clients call it when they negotiate, which happens on every start and reconnect, cache the result, and call it again when a request comes back `401`, retrying once. Do token renewal inside the factory, and keep tokens short-lived. ## How the token travels | Request | Browser JavaScript client | .NET client outside the browser | |---|---|---| | `POST /negotiate` | `Authorization: Bearer` header | header | | Long-polling `GET` and `POST` | header | header | | Server-Sent Events stream (`EventSource`) | `?access_token=` | header | | Server-Sent Events sends (`POST`) | header | header | | WebSocket upgrade | `?access_token=` | header | The query string appears only where the browser API leaves no choice: `new WebSocket(url)` and `new EventSource(url)` cannot add custom request headers. ## Reading it on the server `AddJwtBearer` looks only at the `Authorization` header unless told otherwise. `JwtBearerEvents.OnMessageReceived` runs before validation and may set `context.Token`: 1. Read `context.Request.Query["access_token"]`. 2. Check that the request path starts with the hub's path, such as `/hubs/quotes`. 3. If both hold, assign the value to `context.Token`; the handler then validates it like a header token. Scoping by path matters. Accepting query-string tokens on every endpoint would put them into links, browser history and logs for requests that never needed them. Once authentication succeeds, the hub sees the user in `Context.User`, and `Context.UserIdentifier` comes from the `ClaimTypes.NameIdentifier` claim by default. ## What the query string costs - **Logs.** `Microsoft.AspNetCore.Hosting` writes "Request starting ..." at Information level with the path and query string, so the token lands in server logs. Raise that category to Warning, or log requests with your own middleware that drops `access_token`. Proxies in front of the app may log URLs too. - **HTTPS is mandatory.** The query string is encrypted in transit like a header, but only over TLS. - **Lifetime.** The token is validated when the connection is established, and SignalR keeps that principal for the connection's lifetime. An expired or revoked token does not close an open WebSocket. `HttpConnectionDispatcherOptions.CloseOnAuthenticationExpiration`, `false` by default, closes connections when the authenticated token expires, after which the client must reconnect with a fresh token. ## Reading the symptoms - **Works over long polling, 401 over WebSockets.** The classic sign that `OnMessageReceived` is missing: long polling sends the header, WebSockets send the query value nobody reads. - **401 on every transport.** The token is missing or invalid, or `accessTokenFactory` returns nothing; check the negotiate request first. - **401 only on some hubs.** The path check in `OnMessageReceived` does not match the hub's mapped path, for example `/hub` against `/hubs/quotes`. ## Behind the corporate proxy When the proxy blocks WebSockets and the client falls back to long polling, every request carries the header, so `OnMessageReceived` is not involved. The same handler code works for both paths because it only acts when a query-string token is present on a hub path.

  • Does the .NET SignalR client also put the token in the query string?
    Not outside the browser. A .NET client in a console app or service can set headers on every transport, including the WebSocket upgrade, so it sends `Authorization: Bearer`. Running inside the browser, as in Blazor WebAssembly, it hits the same WebSocket API limit and appends `access_token` too. Either way, browser users need `OnMessageReceived` on the server.
  • What happens to an open SignalR WebSocket connection when its access token expires?
    By default nothing: the principal captured at connect time stays in `Context.User` and the connection keeps working. Setting `CloseOnAuthenticationExpiration = true` in the `MapHub` options closes connections whose authentication carries an expiry once it passes; the client must reconnect with a new token and misses messages sent while it was closed.
  • How do you keep access_token values out of the request logs?
    The token appears in the `Microsoft.AspNetCore.Hosting` "Request starting" message, written at Information level with the query string. Set that category's minimum level to Warning, or replace it with request logging that strips the `access_token` value. Check proxy and load-balancer access logs too, since they record URLs independently of the app.

  • Browsers let the SignalR client set an Authorization header on the WebSocket upgrade.
  • AddJwtBearer reads access_token from the query string on its own.
  • Accepting query-string tokens on every endpoint is fine because HTTPS encrypts them.
  • A SignalR connection is closed automatically as soon as its bearer token expires.
  • Long-polling requests also carry the token in the access_token query value.