Applying Authentication in SignalR
Learn to apply authentication in SignalR applications.
We'll cover the following...
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:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerdotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
Then, we'll open the Program.cs
file of the project and add the following namespace references:
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:
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. ...