Authentication and Authorization for SignalR Persistent Connections (SignalR 1.x)

by Patrick Fletcher, Tom FitzMacken

Note

This article refers to ASP.NET SignalR. If you're thinking about using SignalR to enable real-time scenarios with Java, Node.js, or in a serverless scenario, take a look at ASP.NET Core SignalR. If you've already used ASP.NET SignalR, take a look at the version differences page to understand the differences in the versions and the improvements in ASP.NET Core SignalR. Finally, if you know you'll be running your real-time apps in Microsoft Azure, take a look at the Azure SignalR Service, as it provides cloud-based scale-out once your apps need it.

This topic describes how to enforce authorization on a persistent connection. For general information about integrating security into a SignalR application, see Introduction to Security.

Enforce authorization

To enforce authorization rules when using a PersistentConnection you must override the AuthorizeRequest method. You cannot use the Authorize attribute with persistent connections. The AuthorizeRequest method is called by the SignalR Framework before every request to verify that the user is authorized to perform the requested action. The AuthorizeRequest method is not called from the client; instead, you authenticate the user through your application's standard authentication mechanism.

The example below shows how to limit requests to authenticated users.

public class AuthenticatedConnection : PersistentConnection 
{ 
    protected override bool AuthorizeRequest(IRequest request) 
    { 
        return request.User.Identity.IsAuthenticated; 
    } 
}

You can add any customized authorization logic in the AuthorizeRequest method; such as, checking whether a user belongs to a particular role.