SignalR is commonly used in applications that need real-time communication, such as chat systems, notification services, dashboards, multiplayer games, and live tracking applications. Once a client establishes a SignalR connection, it can exchange messages with the server without creating a new HTTP request for every interaction.
However, long-lived connections introduce an authentication challenge. An access token may expire while the SignalR connection is still active. A user may also have their roles changed, their permissions revoked, or their account disabled while the connection remains open.
These situations can create confusing behavior. A client may continue receiving messages even after its access token expires. Another client may suddenly disconnect when it tries to send a message. In some cases, a user whose permissions have changed can continue invoking hub methods because SignalR still holds the identity established when the connection started.
Handling authentication refresh correctly requires more than obtaining a new access token. The client must provide the updated token to SignalR, the server must authenticate it, and the connection must follow the application's authorization rules.
This article explains why authentication refresh problems occur in ASP.NET Core SignalR, how to handle token renewal in existing applications, and how the authentication refresh capability introduced in .NET 11 simplifies the process.
Why SignalR Connections Have Authentication Problems
Consider a mobile application that uses JWT authentication and SignalR for notifications.
When a user signs in, the authentication service issues an access token that expires after a limited period. The application uses this token to establish a SignalR connection.
The connection may remain active for several hours, even though the access token is valid for only a short period.
This creates a difference between the lifetime of the connection and the lifetime of the authentication token.
SignalR captures the authenticated user when the connection is established. It stores the resulting principal and exposes it through Context.User inside hub methods. By default, SignalR does not automatically revalidate that principal throughout the connection's lifetime.
For example, a user connects with the Admin role. Later, an administrator removes that role from the user's account. The existing SignalR connection may still hold the original principal containing the Admin role.
If a hub method checks only the cached principal, the user may continue accessing operations that should no longer be available.
Token expiration creates another issue. By default, an established SignalR connection can continue working after its token expires. However, transports such as Long Polling and Server-Sent Events make additional HTTP requests, which can fail when they no longer have a valid token.
The application therefore needs a clear strategy for handling token expiration, updated credentials, and changes to user permissions.
Provide a Fresh Token Through AccessTokenProvider
The first step is ensuring that SignalR receives the latest access token whenever it makes an HTTP request.
The .NET SignalR client provides the AccessTokenProvider property for this purpose.
A common mistake is reading the access token once when creating the connection and returning the same value every time. If that token expires, subsequent SignalR requests may continue using an expired credential.
Instead, configure the provider to retrieve the current token from the application's authentication service.
public sealed class SignalRConnectionFactory
{
private readonly ITokenService _tokenService;
public SignalRConnectionFactory(
ITokenService tokenService)
{
_tokenService = tokenService;
}
public HubConnection CreateConnection()
{
return new HubConnectionBuilder()
.WithUrl(
"https://api.example.com/hubs/notifications",
options =>
{
options.AccessTokenProvider =
async () =>
{
return await _tokenService
.GetValidAccessTokenAsync();
};
})
.WithAutomaticReconnect()
.Build();
}
}
The GetValidAccessTokenAsync method represents an application-specific token service. It should return the current valid access token and refresh it when necessary.
SignalR calls AccessTokenProvider before making HTTP requests. This allows the client to obtain an updated token rather than repeatedly using the value that existed when the connection was created.
However, this does not mean every established WebSocket connection automatically reauthenticates its cached user. Before .NET 11, obtaining a new token primarily helped with subsequent HTTP requests and new connection attempts. It did not replace the authenticated principal already associated with an existing connection.
That distinction is important when designing a refresh strategy.
Enable Authentication Expiration Handling on the Server
ASP.NET Core SignalR provides the CloseOnAuthenticationExpiration option.
When enabled, the server closes a connection after its authentication ticket expires. The client can then establish a new connection using a valid access token.
Configure the hub in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
var app = builder.Build();
app.MapHub<NotificationHub>(
"/hubs/notifications",
options =>
{
options.CloseOnAuthenticationExpiration = true;
});
app.Run();
This approach is useful when the application needs to ensure that expired authentication does not remain associated with an active connection indefinitely.
The client can use automatic reconnection:
var connection = new HubConnectionBuilder()
.WithUrl(
"https://api.example.com/hubs/notifications",
options =>
{
options.AccessTokenProvider =
GetAccessTokenAsync;
})
.WithAutomaticReconnect()
.Build();
When the connection closes, the client attempts to reconnect according to the configured retry policy. The access token provider can supply a fresh token for the new connection.
There is an important limitation: reconnecting creates a new SignalR connection. The previous connection ID is not preserved, and the client may miss messages during the disconnection period. It may also need to join its previous groups again.
For applications where temporary disconnections are acceptable, this approach can work well. However, applications that need to update authentication without interrupting the connection can use the newer authentication refresh capability.
Use Built-In SignalR Authentication Refresh in .NET 11
.NET 11 introduces authentication refresh for ASP.NET Core SignalR. It allows a client to update its credentials on an active connection without disconnecting and reconnecting.
This is particularly useful for applications with long-lived WebSocket connections. Instead of waiting for token expiration and creating a new connection, the client can send updated credentials while keeping the existing connection active.
The server authenticates the refresh request through its normal authentication and authorization pipeline. If the refreshed identity passes the required checks, SignalR replaces the cached principal associated with the connection.
First, enable authentication refresh on the hub endpoint:
app.MapHub<NotificationHub>(
"/hubs/notifications",
options =>
{
options.CloseOnAuthenticationExpiration = true;
options.EnableAuthenticationRefresh = true;
});
Both settings are important.
EnableAuthenticationRefresh allows the client to update authentication credentials without reconnecting. CloseOnAuthenticationExpiration ensures that a connection is closed if its credentials expire without a successful refresh.
When authentication refresh is enabled, SignalR adds a refresh endpoint alongside the hub's existing negotiation endpoint. For a hub mapped at /hubs/notifications, the refresh endpoint is:
/hubs/notifications/refresh
The client does not need to construct requests to this endpoint manually. The SignalR client handles the refresh protocol.
The server reports the remaining authentication lifetime during negotiation. The client uses that information to schedule a refresh before expiration.
Configure Automatic Authentication Refresh in the .NET Client
The .NET SignalR client supports automatic authentication refresh when the server enables the feature and reports a token lifetime.
The connection can be configured as follows:
var connection = new HubConnectionBuilder()
.WithUrl(
"https://api.example.com/hubs/notifications",
options =>
{
options.AccessTokenProvider =
GetAccessTokenAsync;
})
.WithAuthenticationRefresh(options =>
{
options.EnableAutoRefresh = true;
options.RefreshBeforeExpiration =
TimeSpan.FromMinutes(2);
})
.WithAutomaticReconnect()
.Build();
The AccessTokenProvider supplies the latest credentials. The WithAuthenticationRefresh method configures when the client should request updated authentication.
In this example, the client attempts to refresh authentication two minutes before the reported expiration.
Automatic refresh is enabled by default, and the default refresh lead time is five minutes. The example changes that timing to two minutes.
Automatic scheduling depends on the server reporting a token lifetime. If the authentication scheme does not provide an expiration and the server does not configure a maximum authentication expiration, the client cannot automatically schedule the refresh. An explicit refresh can still be requested.
You can also refresh authentication manually:
TimeSpan? newLifetime =
await connection.RefreshAuthenticationAsync();
This is useful when the application obtains updated credentials after a user changes permissions, completes a sign-in process, or refreshes a token through an authentication service.
The returned value represents the new token lifetime reported by the server.
Handle Authentication Refresh Failures
Automatic refresh does not guarantee that every refresh attempt will succeed. The authentication server may reject a token, the user's session may have expired, or the refreshed identity may not satisfy the application's authorization rules.
The .NET SignalR client exposes two events that help monitor these situations:
You can register handlers when creating the connection:
connection.AuthenticationRefreshed += context =>
{
Console.WriteLine(
$"Authentication refreshed. " +
$"New lifetime: {context.NewTokenLifetime}");
return Task.CompletedTask;
};
connection.AuthenticationRefreshFailed += context =>
{
Console.WriteLine(
$"Authentication refresh failed: " +
$"{context.Exception.Message}");
return Task.CompletedTask;
};
A failed refresh does not automatically close the connection or trigger another refresh attempt. The connection continues using its existing credentials until they expire. If CloseOnAuthenticationExpiration is enabled, the server closes it when the existing authentication expires.
This means the application should have a clear recovery strategy.
If the refresh failed because of a temporary network problem, the application may allow the user to retry when connectivity returns. If the authentication service rejects the refresh because the session is invalid, the application should request a new sign-in.
Do not treat every refresh failure as a reason to immediately reconnect. Reconnecting with the same invalid token will usually produce another authentication failure.
Validate the Refreshed User on the Server
Authentication refresh must not allow a connection to change from one user identity to another.
SignalR performs a built-in identity check when processing a refreshed principal. It compares identity claims such as sub, ClaimTypes.NameIdentifier, or ClaimTypes.Upn.
For example, suppose a connection was established for user 100. The refreshed token must still represent user 100. If the new token represents user 200, SignalR rejects the refresh.
The refreshed principal can contain updated roles, scopes, or other claims, provided the connection still represents the same SignalR user.
Applications can add their own validation using the OnAuthenticationRefresh callback.
app.MapHub<NotificationHub>(
"/hubs/notifications",
options =>
{
options.CloseOnAuthenticationExpiration = true;
options.EnableAuthenticationRefresh = true;
options.OnAuthenticationRefresh = context =>
{
var tenant = context.NewUser
.FindFirst("tenant")?.Value;
if (tenant != "company-a")
{
return Task.FromResult(false);
}
return Task.FromResult(true);
};
});
This example allows authentication refresh only when the new principal contains the expected tenant claim.
The callback receives information about the previous and refreshed principals, the new expiration, and the connection. It is useful when the application needs to enforce additional rules involving tenants, account status, scopes, or other custom claims.
Returning false rejects the refresh with HTTP 403. The connection keeps its existing principal.
The callback is an additional security check. It cannot approve a refresh that fails SignalR's built-in identity validation.
One important detail is that refreshing authentication does not change Context.UserIdentifier or SignalR's user-based message routing. The connection remains associated with the same SignalR user. If the application's user-routing identity must change, the client needs to establish a new connection.
Fix Refresh Failures Behind a Reverse Proxy
A problem that can be difficult to diagnose occurs when an application runs behind a reverse proxy, API gateway, or web application firewall.
The hub connection may work correctly because the proxy forwards the negotiation and WebSocket requests. However, authentication refresh may fail because the proxy does not forward the new refresh endpoint.
For example, the proxy may allow:
/hubs/notifications
/hubs/notifications/negotiate
But it may not have a routing rule for:
/hubs/notifications/refresh
The client then receives an HTTP error when it attempts authentication refresh.
Review proxy routes, firewall rules, CORS policies, and route-specific authorization policies whenever the refresh endpoint is enabled. The refresh endpoint must be accessible through the same infrastructure path as the other required SignalR requests.
Also check the server response. A 403 generally indicates that the refresh was rejected by identity validation or the custom callback. A 404 can indicate that the connection token does not match an active connection. A 400 can indicate an invalid refresh request or an unsupported connection protocol version.
These status codes provide useful clues before investigating token-generation code.
Understand Authentication Refresh in Older .NET Versions
The built-in authentication refresh feature is available in .NET 11 and later. Applications running earlier versions should not assume that EnableAuthenticationRefresh or RefreshAuthenticationAsync is available.
For older applications, the usual approach is to obtain a new access token through AccessTokenProvider, detect connection closure, and reconnect using the updated token.
A simple reconnection handler can look like this:
connection.Closed += async exception =>
{
await Task.Delay(
TimeSpan.FromSeconds(3));
try
{
await connection.StartAsync();
}
catch (Exception ex)
{
Console.WriteLine(
$"SignalR reconnection failed: {ex.Message}");
}
};
This is a basic example. A production application should use a controlled retry policy with increasing delays, cancellation support, and a limit on retry attempts. It should also distinguish authentication failures from temporary network problems.
After reconnecting, restore the connection's required groups and application subscriptions. A new connection does not automatically inherit the previous connection's group memberships.
For older applications, this reconnect-based strategy remains a practical way to handle token expiration. However, it cannot provide the same uninterrupted authentication update available in .NET 11.
Production Considerations for SignalR Authentication
Authentication refresh should be treated as part of the application's security design, not simply a connection-maintenance feature.
The access token provider should always obtain the latest valid token from the application's authentication service. Avoid storing access tokens in multiple unrelated locations or returning a stale token from a long-lived object.
The token refresh operation should also handle concurrent requests. If several SignalR connections or API calls attempt to refresh the same expired token simultaneously, the application may send multiple refresh requests. A shared token service can coordinate refresh operations so that one renewal updates the stored credentials and other callers reuse the result.
Use HTTPS for all SignalR connections and protect token values from logs. Browser-based SignalR clients may send access tokens in the query string for WebSocket and Server-Sent Events transports because browser APIs restrict custom authorization headers. Ensure that reverse proxies and application logs do not expose these values.
Finally, remember that authentication and authorization are related but separate concerns. A valid token identifies the user, while authorization determines what the user can do. If a user's permissions change, the application must ensure that the updated claims or current authorization data are used when hub methods execute.
Conclusion
Authentication refresh problems in SignalR often occur because developers treat a long-lived connection like a normal HTTP request. A connection can remain active beyond the lifetime of its original access token, and its authenticated principal may not automatically reflect changes to the user's roles or permissions.
For existing applications, AccessTokenProvider, token renewal, and controlled reconnection provide a practical approach. In .NET 11 and later, built-in SignalR authentication refresh allows clients to update credentials on an active connection without reconnecting.
By enabling server-side authentication refresh, supplying fresh tokens, validating the refreshed identity, and monitoring refresh failures, developers can build more reliable real-time applications without weakening authentication rules.
Join the conversation! Your thoughts help the community grow.