Search code examples
c#authenticationsignalrbearer-tokenasp.net-core-signalr

ASPNETCore SignalR authentication with Reference token


We are using ASPNETCore.SignalR 1.1.0 inside our Web API (netcoreapp2.2).

Authentication : We are using IdentityServer4 authentication for our project.

Startup.cs

 services.AddAuthentication("Bearer")
           .AddIdentityServerAuthentication(options =>
           {
               options.Authority = "http://IdentityServerDomainURL:8081/";
               options.RequireHttpsMetadata = false;

               options.ApiName = "name";
               options.ApiSecret = "secret";                

           });

In WebAPI application we have added our SignalR Hub. A JavaScript client connects to this Hub. Following is the code of JS client for connecting to the hub.

var connection = new signalR.HubConnectionBuilder()
                    .withUrl("http://localhost:52177/SignalRHub/", 
                    {
                     accessTokenFactory: () => "referencetokenValue"
                    }).build();

The JS client is passing the Reference token at the time of connecting to the Hub. We need to use Reference token authentication for SignalR in the WebAPI project.

In Microsoft`s site only JWT token authentication documentation for SignalR is provided. Did not find any document anywhere regarding Reference tokens.

Need help in adding the configuration for reference token authentication in startup.cs file.


Solution

  • Found the solution here.

    Any token coming in query string can be added in the request headers as follows:-

    app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.StartsWith("/SignalRHub/"))
                {
                    var bearerToken = context.Request.Query["access_token"].ToString();
    
                    if (!String.IsNullOrEmpty(bearerToken))
                        context.Request.Headers.Add("Authorization", new string[] { "bearer " + bearerToken });
                }
    
                await next();
            });
    

    The above code has to be added in the Configure function of startup class.