How to integrate Microsoft login in nest.js

How to integrate Microsoft login in nest.js

Table of contents

No heading

No headings in the article.

Integrating Microsoft login into a Nest.js application is a straightforward process that can be accomplished using the @nestjs/passport library. In this article, we will walk through the steps required to set up Microsoft login in a Nest.js application.

First, you will need to install the necessary dependencies by running the following command in your project's root directory:

npm install passport passport-azure-ad @nestjs/passport @nestjs/jwt @nestjs/common

Next, you will need to create a new file in your src directory called azure-ad.strategy.ts, which will contain the code for our Microsoft login strategy.

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

@Injectable()
export class AzureADStrategy extends PassportStrategy(Strategy, 'azure-ad') {
    constructor() {
        super({
            clientID: '<YOUR_CLIENT_ID>', //  Replace <YOUR_CLIENT_ID> with your Azure AD App ID
            clientSecret: '<YOUR_CLIENT_SECRET>', // Replace <YOUR_CLIENT_SECRET> with your Azure AD App Secret
            callbackURL: 'http://localhost:3000/auth/azure-ad/callback', //Callback URL
            resource: 'https://graph.windows.net',
            tenant: '<YOUR_TENANT_ID>', // Replace <YOUR_TENANT_ID> with your Azure AD tenant ID
        });
    }

    async validate(accessToken: string, refreshToken: string, profile, done: (err: any, user: any) => void) {
        try {
            const user = {
                accessToken,
                refreshToken,
                profile
            };
            done(null, user);
        } catch (err) {
            done(err, null);
        }
    }
}

After creating the azure-ad.strategy.ts file, you need to import it in the app.module.ts file and add it to the providers array.

import { AzureADStrategy } from './azure-ad.strategy';

@Module({
  imports: [PassportModule],
  providers: [AzureADStrategy],
})
export class AppModule {}

Next, you need to create a new controller file called auth.controller.ts and add the following code which will handle the authentication route:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
    @Get('azure-ad')
    @UseGuards(AuthGuard('azure-ad'))
    async login() {
        // This will redirect the user to the Microsoft login page
    }

    @Get('azure-ad/callback')
    @UseGuards(AuthGuard('azure-ad'))
    async loginCallback(@Req() req)