Introduction

Today we'll learn the process of authorization and authentication for SignalR applications. We can prohibit the user or role to access the hub methods. There are various ways to authenticate and authorize the user in the application using the following procedure:

Authorize

We can apply the Authorize attribute for the user and role to specify the access to a method or hub. We can get this by Microsoft.AspNet.SignalR. We can apply it in the hub or any specific method. When this is applied to any method or a hub, the specified authorization requirement is applied to all the methods in the hub. If the Authorize attribute is not applied, a connected client can access any public method on the hub.

The following code snippet helps to apply the attribute:

using Microsoft.AspNet.SignalR;

namespace SignalRWebApp.hubs

{

[Authorize(Roles = "Admin")]

public class MyAdminHub : Hub

{

}

}

We can also apply the attribute to a specific method that is available to authenticated users only:

namespace SignalRWebApp.hubs

{

public class MyAdminHub : Hub

{

public void Limited()

{

//statements

}

[Authorize]

public void Authenticated()

{

//statements

}

}

}

There are various categories of using this attribute, given below:

Require Authentication

Now with the RequireAuthentication() method, we can require authentication for all hub methods in the application. You use this method when you want to enforce a requirement authentication to all. We cannot specify the requirements for the role with this method. We can only specify that access to the hub methods is restricted to authenticated users.

As an example:

using Microsoft.AspNet.SignalR;

public partial class Startup

{

public void Configuration(IAppBuilder myapp)

{

myapp.MapSignalR();

GlobalHost.HubPipeline.RequireAuthentication();

}

}

The the RequireAuthentication() method is called after the SignalR request, SignalR will throw a InvalidOperationException exception. It is because you cannot add a module to the HubPipeline after the pipeline has been invoked.

Custom made Authorization

We can also customize the authorization by creating a class derived from AuthorizeAttribute and override the UserAuthorized method. For each request, SignalR invokes this method to determine whether the user is authorized to complete the request.

Authentication for Clients

When we have a client as .NET like a console app that interacts with a hub that is limited to authenticated users, you can pass the authentication credentials in a cookie, the connection header or a certificate.

Summary

This article described authorization and authentication for SignalR. You can also learn to apply these in various ways. Thanks for reading.