Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How Do You Secure ASP.NET Core SignalR Hubs with JWTs?

Configure JWT bearer authentication for a SignalR hub, supply tokens through JavaScript or .NET client providers, and handle browser query tokens safely.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To authenticate a SignalR hub with JWTs, configure ASP.NET Core JWT bearer authentication, let each client supply its current token, and protect the hub with authorization. Browser JavaScript needs one extra step: for WebSockets and Server-Sent Events, SignalR sends the token as an access_token query parameter, so the server must read that parameter only on the hub route. Use HTTPS and prevent request logging from exposing the token.

Configure JWT bearer authentication and the hub endpoint

Set up bearer-token validation for the issuer your application actually trusts. Issuer, audience, signing keys, and claim expectations must come from that identity provider; sample values are not production settings. If cookies or multiple authentication schemes are also in use, choose deliberately how hub requests select bearer authentication rather than assuming it is the default.

As an Amazon Associate I earn from qualifying purchases.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Authentication:Authority"];
        options.Audience = builder.Configuration["Authentication:Audience"];

        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;
            }
        };
    });

builder.Services.AddAuthorization();
builder.Services.AddSignalR();

var app = builder.Build();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapHub<ChatHub>("/hubs/chat").RequireAuthorization();
app.Run();

The authority and audience configuration shown is a pattern, not a complete validation policy for every issuer. Configure validation to match your identity provider and application. The query-token handler is needed for browser transports that put the token in the URL; ordinary bearer headers remain the standard route for .NET clients and requests able to set them. Restricting the handler to the mapped hub path prevents query tokens from being accepted indiscriminately elsewhere.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authentication middleware must run before the protected hub endpoint is reached. If your app has more complex routing or multiple schemes, keep the ordering and scheme selection consistent with the rest of its authentication setup.

#1 Best Overall
BookFactory Security Pass Down Log Book, Wire-O, 100 Pages
  • Made in USA - Proudly produced in Ohio by a Veteran-owned business
  • Comprehensive Coverage: This BookFactory log book includes essential fields such as post/shift, time of change, date, weather conditions, and a designated space for detailed notes. This ensures that all relevant information is captured and easily accessible.
  • Sturdy Cover: The trans-lux cover protects the log book from wear and tear, ensuring its longevity and maintaining the integrity of your recorded data.
  • Essential Security Tool: This log book is an indispensable tool for any organization that values security and accountability. It helps to prevent misunderstandings, improve communication, and ensure a smooth transition between shifts.
  • Wire-O with Trans-lux cover, 100 Pages, Dimensions 8.5" x 11" - (Security-Pass-Down) Reorder SKU: LOG-100-7CW-PP(Security-Pass-Down)

Provide a token from each client

Use the application’s existing sign-in or token-management flow to return a valid token. Do not embed a production JWT in client source. SignalR calls the provider before its HTTP requests, so the provider can return a current token rather than a fixed value.

JavaScript client

const connection = new signalR.HubConnectionBuilder()
  .withUrl("/hubs/chat", {
    accessTokenFactory: () => getCurrentAccessToken()
  })
  .build();

getCurrentAccessToken() represents your application’s token retrieval logic; it must return the token expected by the server.

Rank #2
BookFactory Security Incident Report Log Book, Wire-O, 100 Pages
  • Made in USA - Proudly produced in Ohio by a Veteran-owned business
  • This BookFactory log book is for security guards in any sector or business. You can report location, circumstances and report number.
  • There are spaces to log the individual's names address, description and other identifying information. There are also spaces to note others involved, notes, and vehicle information if one was involved
  • Wire-O, 100 Pages, Dimensions 3.5" x 5.25"
  • Reorder SKU: LOG-100-M3CW-PP(Security-Report)

.NET client

var connection = new HubConnectionBuilder()
    .WithUrl(hubUrl, options =>
    {
        options.AccessTokenProvider = () => Task.FromResult(token);
    })
    .Build();

For a .NET client, SignalR sends the token in an Authorization bearer header, so the browser-specific query-string handler is not required for that client path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why browser SignalR uses the access_token query parameter

Browser JavaScript cannot set custom Authorization headers on the browser WebSocket and Server-Sent Events APIs. SignalR therefore sends the token as access_token in the query string for those transports. This is a browser API constraint, not a reason to accept query tokens on every route. With Long Polling, authentication runs on each HTTP request; SignalR nevertheless caches the resulting principal for the lifetime of the connection.

Protect the hub and its methods

RequireAuthorization() on the mapped hub requires an authenticated and authorized principal to connect. You can also apply authorization requirements to individual hub methods when access differs by operation. Authentication establishes who the validated token represents; authorization decides whether that principal may connect or invoke a particular operation.

Base access decisions on claims that are actually present in the validated principal, and confirm their meaning with the issuer. If configuring a SignalR user identifier, do not assume that a name or email claim is unique. Microsoft’s SignalR authentication and authorization guidance warns that the Name claim must be unique when used as the SignalR user identifier.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep query-string tokens out of logs

Use HTTPS for SignalR connections. Microsoft notes that the browser’s query-string token is protected in transit under HTTPS, but a full request URL can still appear in server, proxy, or application logs. ASP.NET Core request logging includes query strings by default, so TLS alone does not prevent credential disclosure through logging.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Inspect logging at the application, hosting, and reverse-proxy layers for hub request URLs.
  • Filter access_token from logged URLs, or raise the relevant hosting logger level to Warning or higher where appropriate.
  • Never use live tokens when checking logs or debugging a connection.

See Microsoft’s SignalR security considerations for its guidance on URL logging and filtering.

Account for connection lifetime and token changes

Refreshing a token through the client provider can supply a new token before subsequent SignalR HTTP requests. It does not automatically replace the authenticated principal on an already-open connection. SignalR also does not automatically revalidate an established connection when a token is revoked or the user’s roles or claims change. If your application requires prompt revocation or updated access decisions, define an explicit connection lifecycle and reconnection strategy suited to its identity and hosting setup.

Verify both client paths and the negotiated transport

  1. Connect the browser client to the exact hub route and confirm which transport it negotiates. Test WebSockets or Server-Sent Events with the route-scoped query-token handler enabled.
  2. Connect a .NET client separately if it is supported, and verify that bearer-header authentication works without relying on the query-token handler.
  3. Check that the hub requires authorization and that any method-level policies use claims present in the validated principal.
  4. Review application and infrastructure logs to confirm that no live access_token is recorded.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.