Integration Angular application with Azure Active Directory authentication – ADAL-Angular 4
What will I do in this article ?
I will try to explain for you how to create integration Azure Active Directory Authentication with Angular application and .NET Core API.
What is ADAL-Angular 4?
ADAL-Angular4 is a simple angular wrapper for Microsoft ADAL.js (Active Directory Authentication Library). Library contains wrapper for connection with Microsoft authentication, interceptor and simple guard. Do not be fooled by the name, library is compatible with Angular 4/5/6/7/8.
How it works?
After implementation ADAL-Angular4 you can choose what components need to be protected by ADAL guard. When guard will detect browser without generated token, library will redirect to Microsoft website with authentication. On .NET Core API side application will communicate with Microsoft to confirm the correctness of token. If token is correct API will return data from controller.
Let’s start
Register Applications
At the beginning you need to register two applications one for Angular application and one for .NET Core API application. To do this log in on https://portal.azure.com, choose from menu Azure Active Directory, on next screen select App Registrations. After the press button New application registration you should see new window with basic inputs to complete.
Configure access to the Web API
Angular Application
Install ADAL-Angular4
Install ADAL-Angular4 library to your Angular application.
NPM website: https://www.npmjs.com/package/adal-angular4
NPM command:
1 |
npm i adal-angular4 |
Implementation
Implement configuration and init adal in app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import { Component } from '@angular/core'; import { AdalService } from 'adal-angular4'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; private adalConfiguration = { tenant: 'TENANT_GUID', clientId: 'APPLICATIONID_GUID', redirectUri: 'LOGIN_REDIRECT_URL', postLogoutRedirectUri: 'LOGOUT_REDIRECT_URL', endpoints: { 'WEB_API_URL': 'APPLICATIONID_WEB_API_GUID' } } constructor(private adal: AdalService) { this.adal.init(this.adalConfiguration); } } |
Now I will explain adalConfiguration parameters:
TENANT_GUID: Is Azure Active Directory ID, you can find it in Azure Active Directory page then in Properties.
APPLICATIONID_GUID: Is the Angular Application ID. To get Application ID
LOGIN_REDIRECT_URL: Is Angular application URL called automatically after the user
LOGOUT_REDIRECT_URL: Is Angular application URL called automatically after the user logout. For instance: http://localhost:4200/logout
WEB_API_URL: Is .NET Core API Application direct URL. For
instance : http://localhost:58434
APPLICATIONID_WEB_API_GUID: Is the .NET Core API Application ID. You can find it in a similiar way as APPLICATIONID_GUID.
Implement guard in app-routing.module.ts and define auth-callback route
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AdalGuard } from 'adal-angular4'; import { AuthCallbackComponent } from './callback/authcallback.component'; const routes: Routes = [ {path: '', component: AppComponent, canActivate: [AdalGuard] }, {path: 'auth-callback', component: AuthCallbackComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } |
Implement ADAL Interceptor in app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthCallbackComponent } from './callback/authcallback.component'; import { AdalService, AdalInterceptor } from 'adal-angular4'; @NgModule({ declarations: [ AppComponent, AuthCallbackComponent ], imports: [ BrowserModule, HttpClientModule, AppRoutingModule, FormsModule ], providers: [AdalService, { provide: HTTP_INTERCEPTORS, useClass: AdalInterceptor, multi: true }], bootstrap: [AppComponent] }) export class AppModule { } |
Create AuthCallbackComponent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Component, OnInit} from '@angular/core'; import { AdalService } from 'adal-angular4'; @Component({ selector: 'app-auth-callback', templateUrl: './auth-callback.component.html', }) export class AuthCallbackComponent implements OnInit { constructor(private adal: AdalService) { } ngOnInit() { this.adal.handleWindowCallback(); //you can do redirect here to another page after login } } |
auth-callback.component.html: You can put here message like „Hello again!”
.NET Core API
Install nuget
Make sure you have installed the Microsoft.AspNetCore.Authentication.AzureAD.UI nuget package. After that you should configure authentication service as AzureADBear.
Implementation
Configure authentication in Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme) .AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options)); services.AddCors((options => { options.AddPolicy("AzurePolicy", builder => builder .WithOrigins("http://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); })); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("AzurePolicy"); app.UseAuthentication(); app.UseMvc(); } |
Add AzureActiveDirectory settings in appsettings.json
1 2 3 4 5 6 |
"AzureAd": { "Instance": "https://login.microsoftonline.com", "Domain": "AD_DOMAIN", "TenantId": "TENANT_GUID", "ClientId": "APPLICATIONID_GUID" } |
AD_DOMAIN: Is Active Directory domain, you can find it in Azure Panel in Azure Active Directory window and at last in Custom domain names.
TENANT_GUID and APPLICATIONID_GUID you can find by analogy to Angular application.
After that all…
Don’t forget to decorate your controller class with Authorize attribute 🙂
1 |
[Authorize] |
In conclusion, I hope I helped you to understand how to implement Azure Active Directory authentication. If you have any question leave me a comment under this post.
If you have