Back to our insights

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

2 minutes read - Technology
Share :

This article is the continuation of the following article: Using OpenIdConnect with Azure AD, Angular5 and WebAPI Core: Angular5 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?

Let us be part of your transformation.

Let’s talk
This site is registered on wpml.org as a development site. Switch to a production site key to remove this banner.