How to Ensure Initial Authentication with Azure AD in Angular App using Guards and NGRX
Image by Zaid - hkhazo.biz.id

How to Ensure Initial Authentication with Azure AD in Angular App using Guards and NGRX

Posted on

Hey there, fellow developer! Are you tired of dealing with authentication woes in your Angular app? Do you want to ensure that your app is secure and guarded against unauthorized access? Look no further! In this comprehensive guide, we’ll show you how to ensure initial authentication with Azure AD in your Angular app using guards and NGRX.

What is Azure AD and Why Do I Need It?

Azure Active Directory (Azure AD) is a cloud-based identity and access management solution that provides single sign-on (SSO) and multi-factor authentication (MFA) capabilities. By integrating Azure AD with your Angular app, you can ensure that only authorized users have access to your app’s resources and data.

But why do you need Azure AD specifically? Well, here are a few compelling reasons:

  • Security**: Azure AD provides an additional layer of security to your app, protecting it from unauthorized access and data breaches.
  • Convenience**: With Azure AD, users don’t need to remember multiple usernames and passwords. They can use their Azure AD credentials to access your app seamlessly.
  • Scalability**: Azure AD scales with your app, so you don’t need to worry about managing user authentication as your app grows.

What are Guards and NGRX?

Before we dive into the implementation, let’s cover some essential concepts:

Guards

In Angular, guards are a type of route guard that allows or denies access to a route based on certain conditions. In our case, we’ll use guards to ensure that users are authenticated with Azure AD before accessing our app’s routes.

Think of guards as bouncers at a nightclub. They check if you’re on the guest list (i.e., authenticated) before letting you in.

NGRX

NGRX is a state management library for Angular that helps you manage your app’s state in a predictable and scalable way. We’ll use NGRX to store and retrieve the user’s authentication token, which is required for Azure AD authentication.

Imagine NGRX as a secure vault where you store your app’s sensitive data, including the user’s authentication token.

Setting up Azure AD and Azure AD Authentication

Before we start coding, let’s set up Azure AD and Azure AD authentication:

  1. Create an Azure AD tenant and register your app.
  2. Register a new application in Azure AD and configure the app’s settings.
  3. Create a client secret and store it securely (e.g., in an environment variable).
  4. Install the `@azure/msal-browser` package using npm or yarn.
  5. Configure the `@azure/msal-browser` package with your Azure AD tenant ID and client ID.

For a step-by-step guide on setting up Azure AD and Azure AD authentication, refer to the official Microsoft documentation.

Implementing Initial Authentication with Guards and NGRX

Now that we have Azure AD set up, let’s implement initial authentication with guards and NGRX:

Step 1: Create an NGRX Store

Create a new file called `auth.reducers.ts` and add the following code:

import { createReducer } from '@ngrx/store';
import { initialState } from './auth.state';

const authReducer = createReducer(
  initialState,
  {
    // Add authentication token to the store
    ADD_AUTH_TOKEN: (state, { token }) => ({ ...state, token }),
    // Remove authentication token from the store
    REMOVE_AUTH_TOKEN: (state) => ({ ...state, token: null }),
  }
);

export function reducer(state = initialState, action) {
  return authReducer(state, action);
}

Step 2: Create an NGRX Effect

Create a new file called `auth.effects.ts` and add the following code:

import { Injectable } from '@angular/core';
import { Actions, ofType, createEffect } from '@ngrx/effects';
import { tap, exhaustMap, map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import {AzureADAuthService} from '../azure-ad-auth.service';

@Injectable()
export class AuthEffects {
  // Initialize the authentication service
  constructor(private actions$: Actions, private azureADAuthService: AzureADAuthService) {}

  // Create an effect to authenticate with Azure AD
  authenticate$ = createEffect(
    () => this.actions$.pipe(
      ofType('[Auth] Authenticate'),
      exhaustMap(() => {
        return this.azureADAuthService.authenticate().pipe(
          map((response) => {
            // Add the authentication token to the store
            return { type: '[Auth] Add Token', token: response.accessToken };
          }),
          catchError((error) => of({ type: '[Auth] Authentication Failed', error })),
        );
      }),
    ),
    { dispatch: true }
  );
}

Step 3: Create an Azure AD Authentication Service

Create a new file called `azure-ad-auth.service.ts` and add the following code:

import { Injectable } from '@angular/core';
import { PublicClientApplication } from '@azure/msal-browser';

@Injectable({
  providedIn: 'root'
})
export class AzureADAuthService {
  private clientApp: PublicClientApplication;

  constructor() {
    // Initialize the Azure AD client application
    this.clientApp = new PublicClientApplication(
      'your_azure_ad_tenant_id',
      'https://login.microsoftonline.com/' + 'your_azure_ad_tenant_id'
    );
  }

  // Authenticate with Azure AD
  authenticate(): Promise {
    return this.clientApp.acquireTokenSilent({
      scopes: ['https://graph.microsoft.com/.default'],
    }).then((response) => {
      return response.accessToken;
    });
  }
}

Step 4: Create a Guard

Create a new file called `auth.guard.ts` and add the following code:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Store } from '@ngrx/store';
import { select, selectSnapshot } from '@ngrx/store';
import { selectAuthToken } from '../auth.selectors';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private store: Store, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return this.store.select(selectAuthToken).toPromise().then((token) => {
      if (!token) {
        // Redirect to login page if no authentication token is found
        this.router.navigate(['/login']);
        return false;
      }
      return true;
    });
  }
}

Putting it All Together

Now that we’ve implemented the NGRX store, effect, Azure AD authentication service, and guard, let’s put it all together:

  1. Add the `AuthGuard` to your app’s routes:
  2. import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { AuthGuard } from './auth.guard';

    const routes: Routes = [
    {
    path: '',
    canActivate: [AuthGuard],
    children: [
    // Add your app's routes here
    ]
    }
    ];

    @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
    })
    export class AppRoutingModule {}

  1. In your app component, dispatch the authentication action:
  2. import { Component, OnDestroy, OnInit } from '@angular/core';
    import { Store } from '@ngrx/store';
    import { select, selectSnapshot } from '@ngrx/store';
    import { authActionTypes } from './auth.actions';

    @Component({
    selector: 'app-root',
    template: '<router-outlet></router-outlet>'
    })
    export class AppComponent implements OnInit, OnDestroy {
    constructor(private store: Store) {}

    ngOnInit(): void {
    // Dispatch the authentication action
    this.store.dispatch({ type: '[Auth] Authenticate' });
    }
    }

That's it! You've successfully implemented initial authentication with Azure AD in your Angular app using guards and NGRX. Your app is now secure and protected against unauthorized access.

Conclusion

In this comprehensive guide, we've covered the importance of Azure AD, the role of guards and NGRX in Angular, and the step-by-step process of implementing initial authentication with Azure AD using guards and NGRX. By following these instructions, you can ensure that your Angular app is secure, scalable, and protected against unauthorized access.

Remember to stay vigilant and monitor your app's authentication and authorization mechanisms regularly to prevent any potential security breaches.

Further Reading

If you want to dive deeper into Azure AD, guards, and NGRX, here are some recommended resources:

Leave a Reply

Your email address will not be published. Required fields are marked *