In this lesson, you will learn how to enforce identity-based security on your SignalR Hubs using standard ASP.NET Core JWT authentication.
When you move beyond public chat rooms, you need to ensure that only authenticated users can invoke hub methods. SignalR integrates seamlessly with ASP.NET Core’s authentication middleware, but there is one critical detail: because SignalR’s initial handshake often happens over WebSockets (which don’t support standard HTTP headers), the client must send the JWT as a query string parameter.
Configuring the Middleware
First, ensure your Program.cs has the authentication and authorization middleware configured. The key is to map the access_token query string parameter to the standard Bearer header during the SignalR connection attempt:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
// Only look for the token in the query string if the request is for our hub
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/chathub"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
Protecting the Hub
Once the middleware is configured, you don't need to manually check tokens inside your methods. You simply decorate your Hub class or specific methods with the [Authorize] attribute. When a client calls a method, the HubContext is automatically populated with the user’s claims, accessible via the Context.User property.
[Authorize]
public class ChatHub : Hub
{
public async Task SendMessage(string message)
{
// Context.User is now fully populated
var username = Context.User?.Identity?.Name;
await Clients.All.SendAsync("ReceiveMessage", username, message);
}
}
By applying these attributes, SignalR will automatically reject unauthorized connection attempts before the OnConnectedAsync lifecycle method is even triggered, protecting your server-side logic from anonymous access.
Key Takeaway: Secure your Hubs by using the [Authorize] attribute and configuring the JWT middleware to extract tokens from the connection's query string during the initial handshake.