In this lesson, you will learn how to secure your SignalR connections by extracting and validating JWTs provided via the query string during the initial handshake.
The Challenge of WebSockets
When a client initiates a SignalR connection over WebSockets, the browser’s standard Authorization header cannot be set manually due to protocol limitations. While browsers automatically handle cookies, many modern, cross-platform, or mobile clients rely on JWTs (JSON Web Tokens). Since we cannot inject headers during the upgrade process, we must pass the token through the query string.
Intercepting the Handshake
To authorize the connection, we configure the JwtBearer options within the AddAuthentication middleware. We must tell the server to look for the token not just in the Authorization header, but also in the query string under a specific parameter name (e.g., access_token).
Here is how you implement this extraction logic:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub, extract the token from the query string
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
path.StartsWithSegments("/chatHub"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
Why This Matters
By setting context.Token manually inside the OnMessageReceived event, the JWT authentication handler treats the incoming request as if it had the correct Authorization: Bearer <token> header. The standard [Authorize] attribute on your Hub class will then function seamlessly, validating the claims, signature, and expiration of the token before the persistent connection is ever established. This ensures that only authenticated clients can upgrade from an HTTP request to a stateful WebSocket connection.
Key Takeaway: By intercepting the OnMessageReceived event in your JWT configuration, you can safely extract and validate tokens from the SignalR handshake query string, enabling robust security for WebSocket-based communication.