...

/

Applying Authentication in SignalR

Applying Authentication in SignalR

Learn to apply authentication in SignalR applications.

Overview

We'll first enable authentication middleware on our SignalR server application. Next, we'll apply access restrictions to the SignalR Hub, so only authenticated users would be allowed to access it. Finally, we'll ensure that our clients are authenticated.

Setting up authentication on SignalR server

To apply authentication to our SignalR Hub, we first need to configure and enable authentication middleware. Before we do this, we need to ensure that the JwtBearer and OpenIdConnect packages have been added to our SignalRServer project. To add them, we can either locate and install them via the NuGet package manager of our IDE, or execute the following commands inside the project folder:

Press + to interact
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
Press + to interact

Then, we'll open the Program.cs file of the project and add the following namespace references:

Press + to interact
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

Then, we'll add and configure OpenID Connect and cookie authentication middleware by adding the following code anywhere before the builder.Build method is called:

Press + to interact
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "webAppClient";
options.ClientSecret = "webAppClientSecret";
options.ResponseType = "code";
options.CallbackPath = "/signin-oidc";
options.SaveTokens = true;
options.RequireHttpsMetadata = false;
})

So, this is what we are doing here. We are first setting the default authentication scheme and the default challenge scheme. OIDC stands for OpenID Connect, so we are just telling our middleware that this is the authentication mechanism that we are using. And we are using cookie authentication by default.

We can’t use cookie authentication unless we add a handler for it. And this is precisely what the AddCookie method does. We just add the name of the authentication scheme to it that we have set as default.

Then we configure our OpenID Connect options. This is where we configure our client. Normally, all of these options would come from a configuration file and ...