SHARE:

Using OpenIdConnect with Azure AD, Angular5 and WebAPI Core: WebAPI configuration

 

Installing required packages

There is only one required package to achieve our Web Api protection with a JWT.

Install https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer/

PM> Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 2.0.1

Configure your Web API in Startup.cs:

using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApiJwtBearer
{
   public class Startup
   {
      public Startup(IConfiguration configuration)
      {
         Configuration = configuration;
      }

      public IConfiguration Configuration { get; }

     //This method gets called by the runtime. Use this method to add services to the container.
     public void ConfigureServices(IServiceCollection services)
     {
        services.AddAuthentication(options =>
        {
           options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
           options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
           options.Authority = "https://login.microsoftonline.com/136544d9-038e-4646-afff-10accb370679"; <- tenantId
           options.Audience = "257b6c36-1168-4aac-be93-6f2cd81cec43"; <- clientId
           options.TokenValidationParameters.ValidateLifetime = true;
           options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
       });

       services.AddAuthorization();

       services.AddMvc();
    }

    //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       if (env.IsDevelopment())
       {
          app.UseDeveloperExceptionPage();
       }

      app.UseAuthentication();

      app.UseCors(builder => builder
      .AllowAnyOrigin()
      .AllowAnyMethod()
      .AllowCredentials()
      .AllowAnyHeader());
      app.UseMvc();
   }
 }
}

Now you should be done 🙂

Let’s see what happen if we test it :

 

Nice isn’t it? 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: