DEV Community

random_person
random_person

Posted on

Azure Active Directory Integration in Angular and React

Overview
This guide provides a full walkthrough for implementing authentication and authorization using Azure Active Directory (AAD) in Angular and React applications. It includes architecture flow, access request procedures, official library usage, and security best practices. It is complemented by fully working demo apps as reference implementations.

Architecture Flow

1.1 Components Overview
Client App (SPA): Angular or React frontend

Azure AD: Identity Provider (IdP)

Protected API (Optional): Backend with protected endpoints (Node.js, .NET, etc.)

1.2 Authentication Flow
User accesses the SPA.

SPA redirects user to Azure AD for login.

Azure AD authenticates the user.

Azure AD returns an ID Token and optionally an Access Token.

SPA stores the token and uses it to access protected resources or APIs.

Requesting Access / App Registration in Azure

2.1 Register Your App in Azure AD
Go to Azure Portal

Navigate to Azure Active Directory > App registrations

Click New registration

Set:

Name: My Angular App or My React App

Redirect URI:

Angular: http://localhost:4200/

React: http://localhost:3000/

Click Register

2.2 Configure Authentication
Under Authentication tab:

Enable ID tokens

Add redirect URIs for local dev and production

2.3 Expose an API (optional)
In Expose an API:

Add scopes like api.read, api.write for backend access control

Angular Integration

3.1 Install Required Packages

npm install @azure/msal-browser @azure/msal-angular
Enter fullscreen mode Exit fullscreen mode

3.2 MSAL Configuration (in app.module.ts)

import { PublicClientApplication, InteractionType } from '@azure/msal-browser';
import {
  MsalModule,
  MsalInterceptorConfiguration,
  MsalGuardConfiguration,
  MSAL_INSTANCE,
  MSAL_GUARD_CONFIG,
} from '@azure/msal-angular';

export function MSALInstanceFactory() {
  return new PublicClientApplication({
    auth: {
      clientId: '<YOUR-CLIENT-ID>',
      authority: 'https://login.microsoftonline.com/<TENANT-ID>',
      redirectUri: 'http://localhost:4200',
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: true,
    },
  });
}

@NgModule({
  imports: [
    MsalModule.forRoot(
      MSALInstanceFactory(),
      {
        interactionType: InteractionType.Redirect,
        authRequest: { scopes: ['user.read'] },
      },
      {
        interactionType: InteractionType.Redirect,
        protectedResourceMap: new Map([
          ['https://graph.microsoft.com/v1.0/me', ['user.read']],
        ]),
      }
    ),
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

3.3 Use MsalGuard for Route Protection

const routes: Routes = [
  {
    path: 'profile',
    component: ProfileComponent,
    canActivate: [MsalGuard],
  },
];
3.4 Login and Logout
ts
Copy
Edit
import { MsalService } from '@azure/msal-angular';

constructor(private authService: MsalService) {}

login() {
  this.authService.loginRedirect();
}

logout() {
  this.authService.logoutRedirect();
}
Enter fullscreen mode Exit fullscreen mode

React Integration

4.1 Install Required Packages

npm install @azure/msal-browser @azure/msal-react
Enter fullscreen mode Exit fullscreen mode

4.2 MSAL Configuration
// src/authConfig.js

export const msalConfig = {
  auth: {
    clientId: '<YOUR-CLIENT-ID>',
    authority: 'https://login.microsoftonline.com/<TENANT-ID>',
    redirectUri: 'http://localhost:3000',
  },
};

export const loginRequest = {
  scopes: ['user.read'],
};

Enter fullscreen mode Exit fullscreen mode

4.3 Wrap App with MsalProvider

import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { msalConfig } from './authConfig';
import App from './App';

const msalInstance = new PublicClientApplication(msalConfig);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <MsalProvider instance={msalInstance}>
    <App />
  </MsalProvider>
);
Enter fullscreen mode Exit fullscreen mode

4.4 Use AuthenticatedTemplate and Login Hooks

import {
  useMsal,
  useIsAuthenticated,
  AuthenticatedTemplate,
  UnauthenticatedTemplate,
} from '@azure/msal-react';

const LoginButton = () => {
  const { instance } = useMsal();
  return <button onClick={() => instance.loginRedirect()}>Login</button>;
};

const LogoutButton = () => {
  const { instance } = useMsal();
  return <button onClick={() => instance.logoutRedirect()}>Logout</button>;
};

const MainContent = () => {
  const isAuthenticated = useIsAuthenticated();
  return (
    <>
      <AuthenticatedTemplate>
        <h2>Welcome!</h2>
        <LogoutButton />
      </AuthenticatedTemplate>
      <UnauthenticatedTemplate>
        <h2>Please sign in.</h2>
        <LoginButton />
      </UnauthenticatedTemplate>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode
  1. Best Practices 5.1 Token Storage Use localStorage only if necessary; prefer sessionStorage to reduce token lifetime risks.

Avoid storing tokens in cookies unless HTTP-only and secure.

5.2 Security Recommendations
Always validate scopes.

Refresh tokens securely (MSAL handles this internally).

Use HTTPS for redirect URIs.

Enable Conditional Access policies in Azure AD for sensitive apps.

5.3 Environment Management
Never hardcode client IDs in shared codebases

Use environment variables for:

Client ID

Tenant ID

Redirect URIs

  1. Resources Microsoft Identity Platform Docs

MSAL.js GitHub

React + MSAL Sample

Angular + MSAL Sample

Top comments (0)