iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
To authenticate an ASP.NET Core SignalR hub with JWTs, configure JWT bearer validation for your actual issuer, give each client an access-token provider, and protect the hub with authentication and authorization middleware. Browser JavaScript needs one additional step: for WebSockets and Server-Sent Events, SignalR places the token in an access_token query parameter, so the server must read it only for the hub route and logs must not expose it.
Configure JWT bearer authentication and the hub endpoint
JWT authentication validates a token and builds the authenticated user principal. Authorization then determines whether that principal may connect to a hub or call a particular hub method. Configure both deliberately: valid authentication alone does not grant access to every hub operation.
In Program.cs, register JWT bearer authentication with the real issuer and validation settings used by your identity provider, register SignalR, and ensure authentication and authorization middleware run before the hub endpoint. The example below shows the shape of the configuration; replace the issuer and route with your application’s real values. Do not deploy placeholder issuer, audience, or signing-key values.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsusing Microsoft.AspNetCore.Authentication.JwtBearer;
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://identity.example.com";
// Configure audience and other validation settings for your issuer.
});
builder.Services.AddAuthorization();
builder.Services.AddSignalR();
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapHub<ChatHub>("/hubs/chat");
The authority, audience, signing-key validation, and expected claims depend on how your application issues tokens. Confirm that the validated principal contains the claims your authorization rules actually use. If cookies or multiple authentication schemes are also configured, explicitly select the bearer scheme for hub requests or use a policy scheme that routes requests appropriately; otherwise the default scheme may not be the one you intend.
#1 Best Overall
Microsoft’s ASP.NET Core 10.0 SignalR authentication and authorization guidance documents the bearer setup and middleware pipeline.
Read browser access tokens only on the hub route
Browser JavaScript cannot attach a custom Authorization header through the browser WebSocket and Server-Sent Events APIs. For these transports, SignalR sends the token from accessTokenFactory as the access_token query parameter. Configure JWT bearer middleware to copy that parameter into the token field—but only when the request targets the hub path.
Rank #2
using Microsoft.AspNetCore.Authentication.JwtBearer;
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://identity.example.com";
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
path.StartsWithSegments("/hubs/chat"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
Use the same route in the path check and MapHub, adjusting both if your hub uses a different URL. Scoping the handler prevents a query parameter on an unrelated endpoint from being treated as a bearer token. Standard bearer headers remain the normal route for clients and requests that can set them.
Provide tokens from each SignalR client
JavaScript client
Set accessTokenFactory in withUrl. Read the token from the application’s existing sign-in or session flow rather than embedding a production token in client source. Because SignalR calls the provider before its HTTP requests, the provider can return a current token when a request is made.
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/chat", {
accessTokenFactory: () => getCurrentAccessToken()
})
.build();
.NET client
For the .NET SignalR client, set AccessTokenProvider in the WithUrl options. Supply the token through your application’s identity flow.
var connection = new HubConnectionBuilder()
.WithUrl(hubUrl, options =>
options.AccessTokenProvider = () => Task.FromResult(token))
.Build();
Unlike browser WebSocket and Server-Sent Events requests, the .NET client can send the token as an Authorization bearer header. It does not need the query-token handler described above for that client path. Microsoft documents the client token-provider APIs in its SignalR client configuration reference.
Rank #4
Understand token handling by client and transport
| Client or request context | Token handling | Server-side implication |
|---|---|---|
| Browser JavaScript using WebSockets or Server-Sent Events | accessTokenFactory; SignalR sends access_token in the query string because browser APIs cannot set custom Authorization headers |
Use a hub-route-scoped OnMessageReceived handler, HTTPS, and logging controls |
| .NET client | AccessTokenProvider; token is sent in an Authorization bearer header |
The browser query-token handler is not needed for this client path |
| Long Polling or other multiple-request connections | Authentication runs on each request, while SignalR caches the resulting principal for the connection lifetime | Repeated requests do not automatically refresh the connection’s roles or claims |
Protect hub access and individual methods
Apply the authorization policy appropriate to your application to the hub and, where access differs by operation, to individual hub methods. Check that the validated principal has the claim types and values those policies expect. A user’s display name or email is not automatically a safe universal identifier; if you configure SignalR user IDs from a name claim, verify that the claim is unique in your identity system.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →For example, apply an authorization policy to the hub class or a method using ASP.NET Core authorization attributes. Define the policy and its required claims or roles for your application rather than relying on an assumed claim name.
[Authorize(Policy = "ChatAccess")]
public class ChatHub : Hub
{
[Authorize(Policy = "CanSendMessages")]
public Task SendMessage(string message)
{
// Handle the authorized operation.
return Task.CompletedTask;
}
}
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Keep query-string tokens out of logs
Use HTTPS for hub connections. Microsoft notes that a browser query-string token is protected in transit by HTTPS, but the full request URL may still be recorded by servers or logging middleware. ASP.NET Core request logging includes query strings by default, so a logged URL can disclose a bearer credential even when transport encryption is working.
- Inspect application, hosting, reverse-proxy, and server logs for hub request URLs.
- Filter
access_tokenfrom logged URLs, or configure relevant request logging to avoid recording the query string. Microsoft’s SignalR security guidance describes raising the relevant hosting logger threshold to Warning or higher, or using middleware that filters the token. - Never treat HTTPS as a substitute for controlling credential logging.
See Microsoft’s ASP.NET Core 10.0 SignalR security considerations for the query-string and logging risks.
Account for the lifetime of an authenticated connection
SignalR associates the authenticated user with a connection. It does not automatically revalidate an established connection when a token is revoked or the user’s roles and claims change. A token provider can return an updated token for subsequent SignalR HTTP requests, but that does not by itself replace the principal on every already-open connection.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →If your application needs prompt revocation or updated permissions to take effect, define an explicit connection lifecycle strategy that fits its identity and hosting setup—for example, how affected connections are identified and disconnected or required to reconnect. The appropriate mechanism depends on the application’s authorization and deployment requirements.
Validate the integration for each supported client
Check browser and .NET client flows independently if your application supports both; their token transport differs. For browser testing, confirm which transport was negotiated and that the route-scoped query-token handler authenticates the connection. For each client, verify that a valid token reaches the hub, a missing or invalid token is rejected, and authorization policies block disallowed hub or method access. Review logs during these checks and use test credentials rather than live tokens.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

