angular - active directory - dotnetcore web api - oauth

So here is a description of what we’ll create in this post:

  • Create an angular app from scratch using the Angular Cli and make it authenticate the user in Azure Active Directory using the MSAL library.
  • Create an Asp.Net Core Web Api from scratch and connect it to Azure Active Directory as well
  • Enable the angular app able to communicate with the web api in an authenticated way using access tokens.

Setting up Azure Active Directory

In Azure Active Directory we have to register 2 applications. You can add an application in the Azure Portal by going to “Azure Active Directory -> App Registrations -> New Registration”

Front End App Registration

We’ll call the first application “demoapp-frontend” and it will contain the configuration for our frontend application.

In here you can also select which AD should be used. If it should only allow users from your tentant or you also want to allow multiple tenants or microsoft accounts.

Lastly we fill in the Redirect URI where we enter “http://localhost:4200” because that is where our Angular application will expect it.

1

After that we press Register and wait for the application to be created. As soon as it is created we can go into the details and write down the Client ID and Tenant ID because we will need it later.

2

Go to the Authentication menu item and check the boxes for Access Tokens and ID Tokens and save the configuration.

 

3

The last step in this app registration is enabling the Oauth Implicit flow. To do this open the manifest and  set “oauth2AllowImplicitFlow” to true

 

4

The last step is enabling the app registration to be used by end users when logging in. You can do this by going to the “API Permissions” menu and Grant consent for the application.

9

Now the app registration is ready and we can continue with the app registration for the API.

API App Registration

We create another app registration called “demoapp-api”. We only need to enter the name and don’t need a redirect url since this app will only check for logged in users and won’t log in the users itself.

Write down the client ID again because we’re going to use it later on.

After we’ve created the app registration go to “Expose an API“. In here we’re going to add a scope by pressing “Add a Scope“.

6

As a scope we’re going to add a scope called “api://<cliendID>/api-access.

Note you can come up with your own scope name or add more scopes later on.

7

After adding the scope we’re going to add the front end app registration as “Authorized Client Application”. Press “Add a Client Application” and enter the client id of the Angular app registration we added.

 

8

This is all we need to do in Azure AD to enable our API and front end application to make use of Azure Active Directory. Now we can start coding our applications. We’ll make use of the MSAL library to connect the angular app to our Web API. Let’s create the Asp.Net Core Web API first that will check for logged in users for all its requests or otherwise will throw a 401 unauthorized.

 

Creating the Asp.Net Core Web API

We’ll be creating a brand new Asp.Net Core 2.2  Web API in this sample by using the CLI. “dotnet new webapi“.

Add an “AzureActiveDirectory” object to your appsettings.json (or add them using secrets ) and fill in your AAD Domain name, Tenant ID and Client ID. (of the API app registration)

 "AzureActiveDirectory": {
 "Instance": "https://login.microsoftonline.com/",
 "Domain": "<yourdomain.onmicrosoft.com>",
 "TenantId": "<yourtenantid>",
 "ClientId": "api://<yourclientid>"
 },

please note to make the client ID be in the form of api://<yourclientid>.

After creating these settings we only need to update the startup.cs to add authentication here to set up AAD integration.

There are a few things to add here (see example startup.cs below)

  • ConfigureServices:
    • Add the services.AddAuthentication method to load our settings to point to the correct AAD app registration.
    • Add Cors. In this example we’ve taken the simples approach by allowing every source. You might want to make this more specific in your own application.
  • Configure
    • Add app.UseCors
    • Add app.UseAuthentication.

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(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));
services.AddMvc();
services.AddCors((options =>
{
options.AddPolicy("FrontEnd", builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
}));
}
// 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();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("FrontEnd");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
}
view rawstartup.cs hosted with ❤ by GitHub
This is everything we need to do to have a working Asp.Net Core Web API with AAD integration. whenever you create a new API Controller just add an [Authorize] attribute to make sure your API calls are authenticated.

Creating the Angular App

We’ll also start with a brand new Angular app creating by using the Angular CLI. Create a new app using “ng new” In the Angular App we will use the MSAL library from Microsoft to connect to Azure Active Directory. MSAL is a new library which should replace the ADAL library Microsoft created earlier. MSAL is created to work with the new v2 endpoints of Azure Active Directory while ADAL only works with the v1 endpoints. Microsoft has created a npm package for MSAL to be used in Angular which makes using MSAL a lot easier. Install this package using “npm i @azure/msal-angular” After installing this package we only need to enable Azure Active Directory in our app.module.ts.   A sample is shown below. What do we need to add:

    • Add the MSAL Module with the correct client ID, and domain (https://login.microsoftonline.com/<tenantid>

 

  • Create a protected resources map. This will function as a guard so each time a resource from one of these URLs is called the right access tokens will be sent along with it.

 

 

  • Fill the Consent Scopes: a list of all the scopes you would like to get access tokens for. This could be User.Read to retrieve the users login name from AD and specific API scopes for your API calls.

 

 

  • Add a HTTP Interceptor so MSAL will add the right tokens and headers to your requests when needed whenever you use a HttpClient.

 

 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MsalModule, MsalInterceptor } from '@azure/msal-angular';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { DemoApiService } from './demoapi.service';
export const protectedResourceMap:[string, string[]][]=[['https://localhost:44388/api/values', ['api://59b02905-8b6b-4665-a702-321e97392416/api-access']] ];
@NgModule({
declarations: [
AppComponent
],
imports: [
MsalModule.forRoot({
clientID: '84750d09-7b12-4a2c-a08c-27e5fc6f51f4',
authority: 'https://login.microsoftonline.com/160c697c-1fc7-465c-9187-67e7080382bb',
consentScopes: [ "user.read", "api://59b02905-8b6b-4665-a702-321e97392416/api-access" ],
protectedResourceMap: protectedResourceMap
}),
BrowserModule,
HttpClientModule,
AppRoutingModule,
],
providers: [ DemoApiService, {
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
view rawapp.module.ts hosted with ❤ by GitHub

Now we can run the application and as soon as we do a network call to an url listed in the protected resources map we will get prompted to log in with our Azure AD Credentials.

In the end connecting your Angular App with Azure Active Directory isn’t that hard, you just have to know exactly what id’s to use where.

Hopefully this will help others in making the connection work smoothly. It took me a few hours to long but managed to get it working with the help and all seeing eyes of my great colleagues ChrisNiels and Thijs