Introduction
In the previous lessons, we built hubs, tracked users, exchanged group messages, displayed notifications, updated live data, and reported long-running progress. This lesson adds the security layer required for a real application. We will create a simple JWT-based login flow without ASP.NET Core Identity, pass the resulting access token to a TypeScript SignalR client, and protect both Web API and Hub endpoints with authentication.
A JWT is a signed access token that carries an identity and, potentially, authorization claims. Before accepting it, the server must validate its signature, issuer, audience, and expiration. For teaching purposes, this lesson uses an in-memory user and a symmetric signing key. In production, prefer an OAuth 2.0 or OpenID Connect identity provider and validate tokens issued with a production-grade key management strategy, commonly using asymmetric signing keys.
1. Prepare the project
Continue with the ASP.NET Core SignalR project from the earlier lessons and add the JWT bearer package:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerDefine shared settings for token creation and validation. In development, use User Secrets or environment variables instead of committing a secret key:
{
"Jwt": {
"Issuer": "RealtimeCourse.Api",
"Audience": "RealtimeCourse.Client",
"Key": "development-only-key-change-this-32-chars",
"Minutes": 30
}
}The key above is only a local demonstration value. In production, store a long, randomly generated secret in a secure secret store. Every application instance that validates the token must have access to the same trusted signing material or to the same identity provider.
2. Configure JWT bearer validation
Configure authentication and authorization in Program.cs before mapping SignalR endpoints:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var jwtSection = builder.Configuration.GetSection("Jwt");
var jwtKey = jwtSection["Key"]
?? throw new InvalidOperationException("Jwt:Key is missing.");
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateIssuer = true,
ValidIssuer = jwtSection["Issuer"],
ValidateAudience = true,
ValidAudience = jwtSection["Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30)
};
options.Events = new JwtBearerEvents
{ =>
{
var accessToken = context.Request.Query["access_token"];
var requestPath = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
requestPath.StartsWithSegments("/hubs/secure"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
builder.Services.AddSignalR();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<SecureHub>("/hubs/secure");
app.Run();The OnMessageReceived handler is essential for browser-based SignalR connections. Standard API requests normally carry a bearer token in the Authorization header. Browser WebSocket and Server-Sent Events APIs have restrictions around custom headers, so SignalR may send the token as an access_token query-string value. Restricting query-string extraction to the expected Hub path prevents the same value from being accepted accidentally by unrelated endpoints.
3. Create a login endpoint without Identity
For a compact demonstration, keep one user in memory. Never store real passwords as plain text. Production applications need a secure user store, password hashing, rate limiting, lockout controls, auditing, and a carefully designed account recovery process.
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
[ApiController]
[Route("api/auth")]
public sealed class AuthController(IConfiguration configuration) : ControllerBase
{
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
var user = request.Email == "ayse@example.com" &&
request.Password == "Pass123!"
? new DemoUser("42", "ayse@example.com", "User")
: null;
if (user is null)
{
return Unauthorized(new { message = "Invalid credentials." });
}
var jwt = configuration.GetSection("Jwt");
var key = jwt["Key"] ?? throw new InvalidOperationException();
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(
signingKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Name, user.Email),
new Claim(ClaimTypes.Role, user.Role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: jwt["Issuer"],
audience: jwt["Audience"],
claims: claims,
expires: DateTime.UtcNow.AddMinutes(
int.Parse(jwt["Minutes"] ?? "30")),
signingCredentials: credentials);
return Ok(new
{
accessToken = new JwtSecurityTokenHandler().WriteToken(token),
expiresAt = token.ValidTo
});
}
}
public sealed record LoginRequest(string Email, string Password);
public sealed record DemoUser(string Id, string Email, string Role);This endpoint exists only to illustrate the token flow. In a production system, authenticate against a secure user directory or identity provider. Also distinguish an API access token from an ID token: the token used to call an API or Hub must be intended for that API.
4. Protect API and Hub endpoints
Protect an API controller with [Authorize]:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/profile")]
[Authorize]
public sealed class ProfileController : ControllerBase
{
[HttpGet]
public IActionResult GetProfile()
{
return Ok(new
{
userId = User.FindFirstValue(ClaimTypes.NameIdentifier),
email = User.Identity?.Name,
isAuthenticated = User.Identity?.IsAuthenticated
});
}
}Protect the Hub as well:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
[Authorize]
public sealed class SecureHub : Hub
{
public Task SendPrivateStatus(string message)
{
var userId = Context.UserIdentifier;
return Clients.User(userId!).SendAsync("statusReceived", new
{
message,
sentAt = DateTimeOffset.UtcNow
});
}
public Task<string> WhoAmI()
{
return Task.FromResult(
Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? "unknown");
}
}The NameIdentifier claim can serve as the SignalR user identifier. If your application uses another claim, implement a custom IUserIdProvider. The selected claim must be unique across users; otherwise, a message sent to one account could be delivered to another account.
5. Log in and connect from TypeScript
First obtain a token from the login endpoint, then configure the SignalR connection with accessTokenFactory:
import { HubConnection, HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
type LoginResponse = {
accessToken: string;
expiresAt: string;
};
let accessToken = "";
let connection: HubConnection;
async function login(): Promise<void> {
const response = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: "ayse@example.com",
password: "Pass123!"
})
});
if (!response.ok) {
throw new Error(`Login failed: ${response.status}`);
}
const result = await response.json() as LoginResponse;
accessToken = result.accessToken;
}
async function connect(): Promise<void> {
connection = new HubConnectionBuilder()
.withUrl("/hubs/secure", {
accessTokenFactory: () => accessToken
})
.configureLogging(LogLevel.Information)
.withAutomaticReconnect()
.build();
connection.on("statusReceived", payload => {
console.log("Status:", payload);
});
await connection.start();
console.log("Secure Hub connected.");
}
await login();
await connect();Because accessTokenFactory can be called before each HTTP request, it is a suitable place to return a refreshed token. Do not continue returning an expired token. Instead, refresh it or obtain a new access token before reconnecting. Carefully evaluate browser token storage in relation to your threat model, XSS exposure, token lifetime, and the rest of your session design.
6. Test invalid-token scenarios
| Scenario | Expected result | What to inspect |
|---|---|---|
| No token is sent | 401 for the API and a rejected Hub connection | accessTokenFactory and middleware order |
| The token is expired | 401 or a failed connection | ValidateLifetime, clock differences, and refresh flow |
| The signature is changed | 401 | Whether the same signing key is configured |
| Issuer or audience differs | 401 | Whether creation and validation settings match |
| The token is valid but the role is insufficient | 403 | [Authorize(Roles = "Admin")] or a policy |
Use browser developer tools to inspect the negotiate request, WebSocket connection, and server logs. When WebSockets or Server-Sent Events are used in a browser, seeing access_token in the query string can be expected. Nevertheless, use HTTPS and make sure reverse proxies, web servers, and application logs do not record token values.
Common mistakes
- Incorrect middleware order:
UseAuthenticationandUseAuthorizationmust run before endpoint execution. - Accepting query tokens everywhere: Read the query-string token only for the specific Hub path that requires it.
- Wrong authentication scheme: If JWT Bearer is not the default scheme, an unqualified
[Authorize]attribute may not behave as expected. - Claim mismatch: Creating a
subclaim but reading a different claim for the SignalR user ID can breakClients.Userdelivery. - Confusing authentication with authorization: Authentication identifies the caller; authorization determines what that caller is allowed to do.
- Long-lived tokens: Use short lifetimes, refresh and revocation strategies, and secure secret management to limit the impact of token theft.
Practice exercise
- Add a second user named
admin@example.comto the demonstration login flow. - Issue the
Adminrole and add a Hub method namedBroadcastMaintenancethat only administrators can call. - Replace the token with a modified value in the TypeScript client and compare API and Hub behavior.
- Set the token lifetime to one minute. Test what happens after expiration, then return a valid token before reconnecting.
- Send an
access_tokenquery parameter to a path other than/hubs/secureand confirm that the JWT handler does not use it.
Conclusion
In this lesson, we created a basic JWT login flow without Identity, configured token validation, and protected both Web API and SignalR Hub endpoints. We also examined why browser transports may carry a token in the query string and why that value must be accepted only on the intended Hub path, over HTTPS, with careful logging. The same foundation can later be extended with a real identity provider, refresh-token management, role and policy authorization, token revocation, and multi-server deployment concerns.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration?view=aspnetcore-9.0
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-jwt-bearer-authentication?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/signalr/security?view=aspnetcore-10.0