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>
  • The client application is ready.
  • Create a Web API project:

    • After creating your API project, please add the following package:
      1. Microsoft.AspNetCore.Authentication.JwtBearer
      2. Microsoft.AspNetCore.Cors
    • Add the following code into the Startup.cs file:
      1. public void ConfigureServices(IServiceCollection services)
      2. {
      3. services.AddControllers();
      4. // Add Cors
      5. services.AddCors(o => o.AddPolicy("default", builder =>
      6. {
      7. builder.AllowAnyOrigin()
      8. .AllowAnyMethod()
      9. .AllowAnyHeader();
      10. }));
      11. services.AddAuthentication(o =>
      12. {
      13. o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
      14. o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
      15. o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
      16. }).AddJwtBearer(opt =>
      17. {
      18. opt.IncludeErrorDetails = true;
      19. opt.Authority = "https://login.microsoftonline.com/c1ec3067-d41e-4053-b90c-d7619dae7650/v2.0";
      20. opt.Audience = "b9535469-bbe7-4a66-8823-4fef098be78e";
      21. });
      22. }
      23. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      24. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      25. {
      26. if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
      27. // Enable Cors
      28. app.UseCors("default");
      29. app.UseRouting();
      30. app.UseAuthentication();
      31. app.UseAuthorization();
      32. app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
      33. }
    • Add a Controller and add the following code into that controller:
      1. using System;
      2. using System.Collections.Generic;
      3. using System.Linq;
      4. using Microsoft.AspNetCore.Authentication.JwtBearer;
      5. using Microsoft.AspNetCore.Authorization;
      6. using Microsoft.AspNetCore.Mvc;
      7. using Microsoft.Extensions.Logging;
      8. namespace azure_ad_webapi.Controllers
      9. {
      10. [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
      11. [Route("api/home")]
      12. [Consumes("application/json")]
      13. [Produces("application/json")]
      14. [ApiController]
      15. public class HomeController : ControllerBase
      16. {
      17. private static readonly string[] Summaries =
      18. {
      19. "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
      20. };
      21. // private readonly ILogger<HomeController> _logger;
      22. public HomeController()
      23. {
      24. //_logger = logger;
      25. }
      26. [HttpGet]
      27. public IEnumerable<WeatherForecast> Get()
      28. {
      29. var rng = new Random();
      30. return Enumerable.Range(1, 5).Select(index => new WeatherForecast
      31. {
      32. Date = DateTime.Now.AddDays(index),
      33. TemperatureC = rng.Next(-20, 55),
      34. Summary = Summaries[rng.Next(Summaries.Length)]
      35. })
      36. .ToArray();
      37. }
      38. }
      39. }
All code is hosted in GitHub. You can check it for a better understanding.