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

Introduction

 

 

Azure Active Directory (Azure AD) is Microsoft’s multi-tenant, cloud based directory and identity management service. Azure AD combines core directory services, advanced identity governance, and application access management. Azure AD also offers a rich, standards-based platform that enables developers to deliver access control to their applications, based on centralized policy and rules.

OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner. OpenID Connect allows clients of all types, including Web-based, mobile, and JavaScript clients, to request and receive information about authenticated sessions and end-users. The specification suite is extensible, allowing participants to use optional features such as encryption of identity data, discovery of OpenID Providers, and session management, when it makes sense for them.

Five scenarios supported by Azure AD:

In this serie of articles article we will demystify Single Page Application (SPA) scenario:

 

This scenario is named Implicit flow in opposition to basic flow in a full back end web application

  1. The user navigates to the web application.
  2. The application returns the JavaScript front end (presentation layer) to the browser.
  3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD authorization endpoint to request an ID token. This request includes the application ID and reply URL in the query parameters.
  4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
  5. The user signs in on the sign-in page.
  6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the application to validate the token.
  7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to the application’s web API back end.
  8. The browser calls the application’s web API back end with the access token in the authorization header.

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? 🙂

Code quality: Using CodeAnalysis.FxCopAnalyzers and Stylecop in .NET Core 2 applications

 

Introduction

Why Code quality is important? Because correctness, maintainability, and even elegance are all involved in creating great code.

Code Quality is a fascinating subject, which comprises a mixture of knowledge, experience, guidelines, principles, patterns and conventions. And if that wasn’t enough, they all should be carefully adapted to each particular team and use case.

The subject gets even more confusing when you start considering tooling. However, choosing the right tools for each team and use case will make achieving quality code simpler.

This article contains an introduction to the Code Quality subject in the .Net Core ecosystem.

CodeAnalysis.FxCopAnalyzers

There are several analyzers available, the most interesting ones in my opinion are:

  • Microsoft.AnalyzerPowerPack
  • Microsoft.CodeAnalysis.FxCopAnalyzers
  • codecracker.CSharp
  • SonarAnalyzer.CSharp
  • StyleCop.Analyzers
  • Microsoft.VisualStudio.Azure.CodeAnalysis (for Azure projects)

In this article I have chosen CodeAnalysis.FxCopAnalyzers.

It can be installed via Nuget Packages, it’s easy to install and it uses a ruleset file, you can download a sample here we will see later how to configure it: myrules.ruleset

Installation

Depending the version Visual Studio you have to be careful with what package version you have to install:

If you don’t install the right package with your current version of Visual Studio you may have issues when you compile your project.

For more information you can referer to the GitHub web page: https://github.com/dotnet/roslyn-analyzers#recommended-version-of-analyzer-packages

In my case I have Visual Studio 2017 15.3 so I have to install the version 2.3.0.

StyleCop.Analyzers

StyleCop is like CodeAnalysis, it uses Roslyn Analyzers but does only care about style programming.

Code analysis searches for patterns which may indicate a bug, while StyleCop is simply enforcing style rules, a simple convention used by your team.

Installation

After installing the Nuget package add in your solution items folder the file stylecop.json (at the same place as your ruleset file), it’s mandatory to add this file to make it work

Then edit your csproj to link your stylecop.json to the project you want to analyze like this (there is no visual tool for this in Visual Studio 2017 for StyleCop):

In the mean time add the ruleset file as follow as well:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>    
     <OutputType>Exe</OutputType>    
     <TargetFramework>netcoreapp2.0</TargetFramework>  
  </PropertyGroup>
  <ItemGroup>  
     <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.3.0-beta1" />    
     <PackageReference Include="StyleCop.Analyzers" Version="1.0.2" />  
  </ItemGroup>    

  <PropertyGroup> 
     <CodeAnalysisRuleSet>$(SolutionDir)\myrules.ruleset</CodeAnalysisRuleSet> 
     <Features>IOperation</Features> 
     <NoWarn></NoWarn>   
  </PropertyGroup>     

  <ItemGroup>    
     <AdditionalFiles Include="$(SolutionDir)\stylecop.json" Link="stylecop.json" />  
  </ItemGroup>  
</Project>

When you are done with that, you can select the rules you want to enable / disable (None, Warning, Error…):

CodeAnalysis rules:

StyleCop rules:

Then when you compile Warnings or Errors appear:

Sample of underlined code:

 

Great isn’t it? 😉

Now your turn to fix analyze your code 😮