Introduction
In this article, we will integrate the Azure Active Directory into an Angular application and get data from a secured web API using a JWT bearer token. There will be 3 steps to integrate the Azure Active Directory into our application.
- Configure Azure active directory for our application:
- Please log into the Azure portal using your credentials.
- Select the Azure Active Directory icon/blade.

- Select the App registration blade and then click new registration. Enter your application name.

- In my case, the name was “azure-ad-integration”. Select the support account types. I selected “Accounts in this directory only”.

- Then you can set “Redirect URI”, although it is an optional field. For my case, I selected “Web” and set its value to http://localhost:4200
- Then click the “Register” button. You'll see the application's Overview or the main registration page.

- The important details here are the client and tenant ids. Note these down in Notepad or similar, you'll need them later.
- Then go to the "Authentication" blade and select "Access Tokens" and "ID tokens" from the implicit grant.
- Then go to "Expose an API" then select "Add a scope" from Scopes defined by this API. Put all the necessary information and save it.

- Your Azure application is ready for production.
- Create an Angular 9 application
- Create an angular application using the following command
ng new azure-ad-client
- Add a package using the following command:
npm install --s @azure/msal-angular
- const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
- @NgModule({
- declarations: [
- AppComponent,
- ProfileComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- HttpClientModule,
- MsalModule.forRoot({
- auth: {
- clientId: environment.clientId,
- authority: environment.authority,
- redirectUri: environment.redirectUrl,
- postLogoutRedirectUri: environment.postLogoutRedirectUri,
- navigateToLoginRequestUrl: true
- }, cache: {
- cacheLocation: 'localStorage',
- storeAuthStateInCookie: isIE, // set to true for IE 11
- },
- }, {
- popUp: !isIE,
- consentScopes: [
- 'user.read',
- 'openid',
- 'profile',
- ],
- protectedResourceMap: [
- ['https://graph.microsoft.com/v1.0/me', ['user.read']]
- ]
- }),
- ],
- providers: [
- {
- provide: LocationStrategy,
- useClass: HashLocationStrategy
- },
- {
- provide: HTTP_INTERCEPTORS,
- useClass: MsalInterceptor,
- multi: true
- },
- MsalService,
- ApiService
- ],
- bootstrap: [AppComponent]
- })
- const routes: Routes = [
- {
- path: '',
- component: ProfileComponent,
- canActivate: [MsalGuard]
- }
- ];
- @NgModule({
- imports: [RouterModule.forRoot(routes)],
- exports: [RouterModule]
- })
Create a new component called profile.
Create a new service in the called api.service.ts into an app/shared folder and add the following code:
- @Injectable({ providedIn: 'root' })
- export class ApiService {
- private baseUrl = environment.apiEndpoint;
- constructor(private http: HttpClient) { }
- getWeathers(): Observable<IWeatherForecast[]> {
- // console.log('Token is ', localStorage.getItem('msal.idtoken'));
- const reqHeader = new HttpHeaders({
- 'Content-Type': 'application/json',
- Authorization: 'Bearer ' + localStorage.getItem('msal.idtoken')
- });
- return this.http.get<IWeatherForecast[]>(this.baseUrl + 'home', { headers: reqHeader }).pipe(
- retry(1),
- catchError(this.errorHandl)
- );
- }
- // Error handling
- errorHandl(error) {
- let errorMessage = '';
- if (error.error instanceof ErrorEvent) {
- errorMessage = error.error.message;
- } else {
- errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
- }
- return throwError(errorMessage);
- }
- }

Weng NgPosted Mar 31, 2021, 8:03 PM
Salam, bro. Thanks for the article. Very helpful and easy to understand. Bless you.
Craig SimonPosted Feb 5, 2021, 3:39 PM
Thank you for this. I'll be investigating how to adapt this AD-based approach for AD B2C. The differences look challenging. If you've got a similar boilerplate for B2C, I'd be delighted to see it.
Hamid KhanPosted Sep 22, 2020, 10:12 PM
Very good concept that you explain................