Yahli Gitzi
Yahli Gitzi

Reputation: 445

Nestjs - Implement Azure-Ad Passport Authentication

How can I implement Azure-Ad Passport Authentication? Can't find any documentation for it, and read online that there are problems with that.

Upvotes: 1

Views: 7361

Answers (1)

Max Sherbakov
Max Sherbakov

Reputation: 1955

Use MSAL for FrontEnd. For Backend use Passport and passport-azure-ad npm. enter image description here

  • Then, you should create your app in Azure AD
  • then, get tenantId and appId from app settings page,
  • then, use code like that to get access token and check user auth.
// my auth-guard.ts

import { AuthGuard, PassportStrategy } from '@nestjs/passport';
import { BearerStrategy } from 'passport-azure-ad';
import { Injectable } from '@nestjs/common';


@Injectable()
export class AzureADStrategy extends PassportStrategy(
  BearerStrategy,
  'azure-ad',
) {
  constructor() {
    super({
      identityMetadata: `https://login.microsoftonline.com/${tenantID}/v2.0/.well-known/openid-configuration`,
      clientID,
    });
  }

  async validate(data) {
    return data;
  }
}

export const AzureADGuard = AuthGuard('azure-ad');

// app.controller.ts

  @UseGuards(AzureADGuard)
  @Get('/api')
  get_api(): string {
    return 'OK';
  }
}

try it should work.

Upvotes: 7

Related Questions