#NestJS Microservices with Passport Authentication

4 messages · Page 1 of 1 (latest)

tranquil wren
#

Architecture Context:
I have a microservices architecture using NestJS, consisting of:
An API Gateway that routes requests.
An Auth Microservice is responsible for handling authentication (using Passport.js).
A User Microservice for user-related data and operations.
The workflow involves the API Gateway receiving login requests from clients and forwarding them to the Auth Microservice, which validates the user credentials (email and password).

Auth Guard:

import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
  constructor() {
    super();
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const activate = await super.canActivate(context);
    if (!activate) {
      return false;
    }
    return true;
  }
}

Passport Strategy

import { Injectable } from '@nestjs/common';
import { RpcException } from '@nestjs/microservices';
import { PassportStrategy } from '@nestjs/passport';

import { Strategy } from 'passport-local';

import { AuthService } from '../auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(email: string, password: string) {
    const user = await this.authService.validateUser(email, password);
    if (!user) {
      console.log('++++++++++++++++++++++++++++++++++++++++++++++++');
      throw new RpcException('Invalid credentials');
    }
    return user;
  }
}

When I return false from the auth guard in the API gateway, I get an internal server error instead of the actual error in the gateway. However, I see the error logged automatically in the Nest

queen island
#

Depending on the way you receive the request you might need a different execution context maybe

#

for example, when doing that via graphql I need a graphql execution context first no idea if there is something special for rpc

#

well, the error might not leave the auth service, it should bubble up the error to the gateway maybe so the gateway can rethrow I guess