Securing Email Synchronization in NestJS: Implementing Dynamic Authentication Strategies in Gmail Sync System

Abdullah Irfan
2 min readMar 7, 2024

--

This is the thirteenth story of series Building a Robust Backend: A Comprehensive Guide Using NestJS, TypeORM, and Microservices. Our purpose is to build an email sync system for Gmail, since we have built the main functionality, now let’s proceed with implementing authentication and authorization. In last story strategies for authentication were missed, so first we will add those.

A strategy is a behavioural software design pattern that enables selecting an algorithm at runtime. More about strategies can be read from here. We will be defining two strategies, one for local auth and other for JWT with roles. We will install passport packages with with npm install passport-jwt passport-local and the code is below:

// src\shared\strategies\jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.SECRET,
passReqToCallback: true,
});
}

async validate(req: Request, payload: any) {
return { id: payload.id, email: payload.email, roles: payload.roles };
}
}
// src\shared\strategies\local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { HttpStatus, Injectable, NotFoundException } from '@nestjs/common';
import customMessage from '../responses/customMessage.response';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor() {
super();
}

async validate(identifier: string, password: string): Promise<any> {
}
}

Next, we will setup users module. This story code is available on GitHub in feature/add-strategies branch. If you appreciate this work, please show your support by clapping for the story and starring the repository.

--

--