Skip to content

Web API Middleware

Oleg Burov edited this page May 20, 2018 · 3 revisions

As you wired up the Auth0 with the Web App, now you need to do same, but with the Web API. You will start with adding authentication service to the service container, which makes it available within the Web API, and then enabling the authentication itself.

Visual Studio

In the file Startup.cs, modify the method ConfigureServices as shown below:

Add Authentication service

The method AddAuthentication registers the authentication services. But this time, it specifies the DefaultAuthenticateScheme and DefaultChallengeScheme as the JWT Bearer. What this means is that when ASP.NET Core checks whether a request is authenticated, it will use the JWT Bearer handler, which you need to register next.

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  ...

  services.AddAuthentication(options =>
  {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  });

  ...
}

Add JwtBearer handler

The method AddJwtBearer registers the JWT Bearer handler.

public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddAuthentication(options =>
  {
    ...
  })
  .AddJwtBearer(options =>
  {
    options.Authority = $"https://{Configuration["Auth0:Domain"]}/";
    options.Audience = Configuration["Auth0:ApiIdentifier"];
  });
  ...
}

Enable Authentication middleware

In the file Startup.cs, modify the method Configure as shown below.

The method UseAuthentication adds authentication middleware to the request pipeline, which enables identity for the Web App.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  ...
  if (env.IsDevelopment())
  {
  ...
  }
  else
  {
  ...
  }

  app.UseAuthentication();

  app.UseHttpsRedirection();
  ...
}

Summary

You now have configured Auth0 as Identity Provider service in the Web API. Where ASP.NET Core uses JWT Bearer token to authenticate a user's permission and validate the token with Auth0 Issuer. In the following tutorial, you'll learn how to protect API endpoints using user's granted scopes.

What's next?

Web API - Authorization