Applying authorization in SignalR

Authentication on its own is good, but it’s rarely sufficient. We don’t only need to ensure that only known users can access your application, we also have to make sure that only those users that are permitted to use a specific resource can access it. This is what the role of authorization is.

There are standard HTTP response codes that demonstrate the difference between authentication and authorization. 401 (Unauthorized) indicates that the user’s credentials haven’t been supplied or are invalid. 403 (Forbidden), on the other hand, is returned when the server is happy with the user’s credentials, but the user doesn’t have special privileges to access a specific resource.

There are several different types of authorization available in ASP.NET Core and all of them are applicable to SignalR. We just need to configure authorization handlers in our application. There are multiple ways of doing it, and we will cover some of them.

Creating a custom requirement

One of the ways of applying authorization is to add a custom requirement class that inherits from the AuthorizationHandler base class. We will create such a class. This will be done by creating a RoleRequirement.cs file inside the SignalRServer project folder. The content of the file will be as follows:

Get hands-on with 1200+ tech skills courses.