Applying Authentication in SignalR
Explore how to enable and configure authentication in SignalR applications to restrict access to hubs only to authenticated users. Learn to set up OpenID Connect and JWT bearer tokens for secure client connections. Understand how to apply authorization attributes in your hub and manage token handling for different client types, enhancing your app's security.
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:
Then, we'll open the Program.cs file of the project and add the following namespace references:
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:
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 ...