Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

Example of registration for Angular application
Example of registration for API application

Configure access to the Web API

Second thing to do in Azure Active Directory is configure access to the Web API. Therefore open registered Angular application and click on the Settings button, after that choose Required permissions. In Required permissions window click Add button and choose registered .NET Core API application after that select checkbox with DELEGATED PERMISSIONS.

Angular Application

Install ADAL-Angular4

Install ADAL-Angular4 library to your Angular application.

NPM website: https://www.npmjs.com/package/adal-angular4

NPM command:

npm i adal-angular4

Implementation

Implement configuration and init adal in app.component.ts

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. 

Azure Active Directory ID

APPLICATIONID_GUID: Is the Angular Application ID. To get Application ID go to Azure Active Directory after that go to App registrations and find your registered Angular application. In detailswindow you should get a column with the Application ID.

Application ID

LOGIN_REDIRECT_URL: Is Angular application URL called automatically after the user authenticate on Microsoft page. For instance: http://localhost:4200/auth-callback

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

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

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

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

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

"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

[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 an extra time you can check my another article how to implement hamburger menu in xamarin.forms

The post Integration Angular application with Azure Active Directory authentication – ADAL-Angular 4 appeared first on Adrian Szeń.



This post first appeared on , please read the originial post: here

Share the post

Integration Angular application with Azure Active Directory authentication – ADAL-Angular 4

×

Subscribe to

Get updates delivered right to your inbox!

Thank you for your subscription

×