Azure AD Auth with MSAL in Angular and ASP.NET Core API
Learn how to implement Azure AD authentication in your Angular app using MSAL and connect it securely with ASP.NET Core Web API. Step-by-step setup included.
Hire our expert Angular developer
We are using Angular 8 Quick starter, first download Angular 8 CLI and then create our project. Consider that server side code has already been developed.
Go to AngularCLI website and follow the steps.
To install the CLI using npm, open a VS Code terminal/console window. If you are on a Mac or Linux type following command.
PS E:\>npm install -g @angular/cli
It takes some time to download the CLI and Installed the NPM packages.
1. Run the CLI command ng new and provide the name my-app, as show below. As we are implementing Identity Server so I given a name as “identityServer-app”
PS C:\> ng new identityServer-app
2. The ng new command prompts you for information about features to include in the initial app project and here are the answers of each:
PS C:\> ng new identityServer-app
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com/documentation/file.SASS_REFERENCE.html#syntax ]
CREATE identityServer -app/angular.json (3958 bytes)
CREATE identityServer -app/package.json (1313 bytes)
This will create required folders to Up and Running with our Application and also install all the NPM packages. This will take some time to finish.
Go to workplace folder (identityServer-app) and type following command on your terminal to install the latest Oidc-client.js
PS C:\identityServer-app> npm install oidc-client –save
you’ll need the latest version of oidc-client, which you can see in package.json
"oidc-client": "^1.10.1"
Create constant object called “ClientSettings” as per below code.
export const ClientSettings = {
authority: "http://localhost:5000",
client_id: "identityserverapp",
redirect_uri: "http://localhost:4200/auth-callback",
post_logout_redirect_uri: "http://localhost:5000/account/login/",
response_type: "code",
scope: "openid profile api",
filterProtocolClaims: true,
loadUserInfo: true,
automaticSilentRenew: true,
silent_redirect_uri: 'http://localhost:4200/silent-refresh'
};
Below is content of the get client setting function which inherited UserManagerSettings class which is part of the oidc-client
export function getClientSettings(): UserManagerSettings {
return {
authority: ClientSettings.authority,
client_id: ClientSettings.client_id,
redirect_uri: ClientSettings.redirect_uri,
post_logout_redirect_uri: ClientSettings.post_logout_redirect_uri,
response_type: ClientSettings.response_type,
scope: ClientSettings.scope,
filterProtocolClaims: ClientSettings.filterProtocolClaims,
loadUserInfo: ClientSettings.loadUserInfo,
automaticSilentRenew: ClientSettings.automaticSilentRenew,
silent_redirect_uri:ClientSettings.silent_redirect_uri
};
}
Create auth.service file and below is content of the auth.service.ts file.
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { User, UserManager, UserManagerSettings } from "oidc-client";
import { BehaviorSubject } from "rxjs";
@Injectable({
providedIn: "root"
})
export class AuthService {
private _authNavStatusSource = new BehaviorSubject(false);
authNavStatus$ = this._authNavStatusSource.asObservable();
private manager = new UserManager(getClientSettings());
private user: User | null;
constructor(private http: HttpClient, private configService: ConfigService) {
super();
this.manager.getUser().then(user => {
this.user = user;
this._authNavStatusSource.next(this.isAuthenticated());
});
}
login() {
return this.manager.signinRedirect();
}
async completeAuthentication() {
this.user = await this.manager.signinRedirectCallback();
this._authNavStatusSource.next(this.isAuthenticated());
}
signinSilentCallback(){
this.manager.signinSilentCallback()
.catch((err) => {
console.log(err);
});
}
isAuthenticated(): boolean {
return (this.user != null && !this.user.expired);
}
get authorizationHeaderValue(): string {
return `${this.user.token_type} ${this.user.access_token}`;
}
get name(): string {
if (this.user !== null && this.user.profile !== undefined){
return this.user.profile.name;
} else {
return "";
}
}
async signout() {
await this.manager.signoutRedirect();
}
}
Here is description of each methods which has been used in auth.service.ts file.
Create authgard service which help to automatically redirect to logged in page if user is not authenticate.
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isAuthenticated()) { return true; }
this.authService.login();
return false;
}
Create auth call back component which will be redirect url of after successfully logged in to identity server. Below is content of the auth-callback.ts component
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { AuthService } from "../core/authentication/auth.service";
@Component({
selector: "app-auth-callback",
templateUrl: "./auth-callback.component.html",
styleUrls: ["./auth-callback.component.scss"]
})
export class AuthCallbackComponent implements OnInit {
error: boolean;
constructor(
private authService: AuthService,
private router: Router
) { }
async ngOnInit() {
await this.authService.completeAuthentication();
this.router.navigate(["/home"]);
}
}
Create Home component which will display after successfully logged in. It is simple component and its routing configuration set to canActive so if user directly use the home link and not authorize then redirect to login page.
Create logout component which we will use when user logout from angular App and we need to redirect to identity server logout screen. Below is code for logout component
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../core/authentication/auth.service';
@Component({
selector: 'app-logout',
templateUrl: './logout.component.html',
styleUrls: ['./logout.component.sass']
})
export class LogoutComponent implements OnInit {
constructor(private authService: AuthService) {
this.authService.signout();
}
ngOnInit() {
}
}
Learn how to implement Azure AD authentication in your Angular app using MSAL and connect it securely with ASP.NET Core Web API. Step-by-step setup included.
Learn how to integrate Okta authentication in Angular using OAuth 2.0 and OIDC. Step-by-step guide for secure login, token handling, and route protection.angular
Step-by-step guide to implement Google OAuth2 authentication in ASP.NET Core. Secure your app with Google sign-in, token validation, and user claims.
Get in touch with Prishusoft – your trusted partner for custom software development. Whether you need a powerful web application or a sleek mobile app, our expert team is here to turn your ideas into reality.