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
In your app.module.ts, add following code:
  1. const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
  2. @NgModule({
  3. declarations: [
  4. AppComponent,
  5. ProfileComponent
  6. ],
  7. imports: [
  8. BrowserModule,
  9. AppRoutingModule,
  10. HttpClientModule,
  11. MsalModule.forRoot({
  12. auth: {
  13. clientId: environment.clientId,
  14. authority: environment.authority,
  15. redirectUri: environment.redirectUrl,
  16. postLogoutRedirectUri: environment.postLogoutRedirectUri,
  17. navigateToLoginRequestUrl: true
  18. }, cache: {
  19. cacheLocation: 'localStorage',
  20. storeAuthStateInCookie: isIE, // set to true for IE 11
  21. },
  22. }, {
  23. popUp: !isIE,
  24. consentScopes: [
  25. 'user.read',
  26. 'openid',
  27. 'profile',
  28. ],
  29. protectedResourceMap: [
  30. ['https://graph.microsoft.com/v1.0/me', ['user.read']]
  31. ]
  32. }),
  33. ],
  34. providers: [
  35. {
  36. provide: LocationStrategy,
  37. useClass: HashLocationStrategy
  38. },
  39. {
  40. provide: HTTP_INTERCEPTORS,
  41. useClass: MsalInterceptor,
  42. multi: true
  43. },
  44. MsalService,
  45. ApiService
  46. ],
  47. bootstrap: [AppComponent]
  48. })
In your app-routing.module.ts file, add the following line:
  1. const routes: Routes = [
  2. {
  3. path: '',
  4. component: ProfileComponent,
  5. canActivate: [MsalGuard]
  6. }
  7. ];
  8. @NgModule({
  9. imports: [RouterModule.forRoot(routes)],
  10. exports: [RouterModule]
  11. })
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:
  1. @Injectable({ providedIn: 'root' })
  2. export class ApiService {
  3. private baseUrl = environment.apiEndpoint;
  4. constructor(private http: HttpClient) { }
  5. getWeathers(): Observable<IWeatherForecast[]> {
  6. // console.log('Token is ', localStorage.getItem('msal.idtoken'));
  7. const reqHeader = new HttpHeaders({
  8. 'Content-Type': 'application/json',
  9. Authorization: 'Bearer ' + localStorage.getItem('msal.idtoken')
  10. });
  11. return this.http.get<IWeatherForecast[]>(this.baseUrl + 'home', { headers: reqHeader }).pipe(
  12. retry(1),
  13. catchError(this.errorHandl)
  14. );
  15. }
  16. // Error handling
  17. errorHandl(error) {
  18. let errorMessage = '';
  19. if (error.error instanceof ErrorEvent) {
  20. errorMessage = error.error.message;
  21. } else {
  22. errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
  23. }
  24. return throwError(errorMessage);
  25. }
  26. }
In your newly created component, please add the following lines of code:
  1. export class ProfileComponent implements OnInit {
  2. name: string;
  3. username: string;
  4. public weatherData: IWeatherForecast[] = [];
  5. constructor(private msalService: MsalService, private apiService: ApiService) { }
  6. ngOnInit(): void {
  7. const account = this.msalService.getAccount();
  8. this.name = account.name;
  9. this.username = account.userName;
  10. this.getWeatherinformation();
  11. }
  12. getWeatherinformation() {
  13. this.apiService.getWeathers().subscribe(res => {
  14. // console.log('data: ', res);
  15. this.weatherData = res as IWeatherForecast[];
  16. });
  17. }
  18. logout() {
  19. localStorage.clear();
  20. this.msalService.logout();
  21. }
  22. }
In your profile.component.html, please add the following code:
  1. Name: {{name}}<br/>
  2. Username: {{username}}
  3. <br/>
  4. <h3>Data From Web API</h3>
  5. <ul>
  6. <li *ngFor="let element of weatherData" [type]="element">
  7. {{element.date}}, {{element.summary}}, {{element.temperatureC}}, {{element.temperatureF}}
  8. </li>
  9. </ul>
  10. <button type='button' name='logOut' id='logout' (click)="logout()">Log Out</button>
All code is hosted in GitHub. You can check it for a better understanding.