Configuring our ASP.NET Core backend to authenticate with Auth0

We can now change our ASP.NET Core backend to authenticate with Auth0. Let's open the backend project in Visual Studio and carry out the following steps:

  1. Install the following NuGet package:
Microsoft.AspNetCore.Authentication.JwtBearer
  1. Add the following using statement to the Startup class:
using Microsoft.AspNetCore.Authentication.JwtBearer;
Make sure the version of the package you select is supported by the version of .NET Core you are using. So, for example, if you are targeting .NET Core 3.0, then select the package version 3.0.0.
  1. Add the following lines to the ConfigureServices method in the Startup class:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme =
JwtBearerDefaults.AuthenticationScheme;

options.DefaultChallengeScheme =
JwtBearerDefaults.AuthenticationScheme;

}).AddJwtBearer(options =>
{
options.Authority = Configuration["Auth0:Authority"];
options.Audience = Configuration["Auth0:Audience"];
});
}

This adds JWT-based authentication specifying the authority and expected audience as the appsettings.json settings.

  1. Let's add the authentication middleware in the Configure method. It needs to be placed between the routing and authorization middleware:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

...
}

This will validate the access token in each request if one exists. If the check succeeds, the user on the request context will be set.

  1. The final step is to add the settings in appsettings.json, which we have referenced:
{
...,
"Auth0": {
"Authority": "https://your-tenant-id.auth0.com/",
"Audience": "https://qanda"
}
}

We will need to substitute our Auth0 tenant ID into the Authority field. The tenant ID can be found in Auth0 to the left of the user avatar:

So, Authority for the preceding tenant is https://your-tenant-id.auth0.com/. The Audience field needs to match the audience we specified in Auth0.

Now that our web API is validating access tokens in the requests, we are going to start protecting some endpoints in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.147.215