In this lesson, you will learn how to apply hub-level authentication to ensure that only verified users can connect to and interact with your SignalR real-time communication streams.
The Problem: Open Communication Channels
By default, a SignalR hub is an open door; once a client connects, they can invoke methods defined in your hub. In a production system, you rarely want anonymous users broadcasting messages or accessing sensitive real-time data. Securing a hub starts by enforcing identity requirements at the point of entry—the connection attempt itself.
Applying Hub-Level Authorization
In ASP.NET Core, securing a hub is as simple as applying the [Authorize] attribute to the class definition. This forces the SignalR middleware to validate the user's credentials—typically via a JWT bearer token or cookie—before the connection is upgraded to a persistent state.
Consider this example:
[Authorize]
public class NotificationHub : Hub
{
public async Task SendUpdate(string message)
{
// Only authenticated users can call this
await Clients.All.SendAsync("ReceiveMessage", Context.User.Identity.Name, message);
}
}
When you decorate the NotificationHub with [Authorize], any client attempting to connect without a valid authentication ticket will receive a 401 Unauthorized response during the handshake process.
Why Hub-Level?
Applying authorization at the hub level is a powerful, "deny-by-default" strategy. It ensures that the entire lifecycle of the connection—from the initial HTTP handshake to subsequent WebSocket frames—is governed by your application's identity policy. Because you have already learned how to implement OIDC flows and handle JWTs, you can pass your existing access tokens through the SignalR connection string or via HTTP headers. Once authorized, the Context.User property within your hub methods becomes fully populated with the user's claims, allowing you to perform granular checks, such as verifying if a specific user has permission to join a particular group or send a specific message.
Key Takeaway: Applying the [Authorize] attribute to your Hub class ensures that the connection handshake is restricted to verified identities, effectively gatekeeping all real-time communication behind your established authentication layer.