Various Ways to Authenticate and Authorize SignalR Hubs

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
  • RequireAuthentication
  • Authentication for Clients

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:

  • [Authorize]: Only authenticated users
  • [Authorize(Roles="Admin, Manager")]: Only authenticated users in the specified roles
  • [Authorize(Users= "User1, User2")]: Only authenticated users with the specified user names

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.

  • Cookie

    When the .NET client interacts with the hub class using Forms Authentication, we need to set the authentication cookie on the connection to manual. We add the cookie to the CookieContainer property on the HubConnection object.
     
  • Windows Authentication

    We can pass the current user's credentials while using the Windows authentication using DefaultCredentials . At first add the reference of Microsoft.AspNet.Clients from the NuGet Gallery.

    AspNet Client Package

    Example:
     

    public class Program

    {

        static void Main(string[] args)

        {

            var appConnection = new HubConnection("http://www.c-sharpcorner.com/");

            appConnection.Credentials = CredentialCache.DefaultCredentials;

            appConnection.Start().Wait();

        }

    }

  • Connection Header

    We can also pass the information of the user in the connection header, if we are not using the cookie. As an example:
     

    public class Program

    {

        static void Main(string[] args)

        {

            var appConnection = new HubConnection("http://www.c-sharpcorner.com/");

            appConnection.Headers.Add(“MyAuthentication”,”token value”);

            appConnection.Start().Wait();

        }

    }
     

  • Certificate

    To verify the user information, we can also pass a client certificate. We can add the client certificate while creating the connection.
     

    public class Program

    {

        static void Main(string[] args)

        {

            var appConnection = new HubConnection("http://www.c-sharpcorner.com/");

            appConnection.AddClientCertificate

            (X509Certificate.CreateFromCertFile("certificate name"));

            appConnection.Start().Wait();

        }

    }


    In the code above, the X509Certificate class is used that provides various ways to create the certificate. The assembly is used for this is System.Security.Cryptography.X509Certificate.

Summary

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

Up Next
    Ebook Download
    View all
    Learn
    View all