Kristóf Varga
Kristóf Varga

Reputation: 67

Nestjs how to pass data from AuthGuard to controller

I have two microservices one for authentication and another for users. I can log in and get a token, and i can use protected routes only when logged in. However I want to use the userId which i get in the AuthGuard's canActivate function, but i cant reach it in the controller. What is the best way to do it?

My auth guard:

import { CanActivate, ExecutionContext, Inject, Logger } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';

export class JwtAuthGuard implements CanActivate {
  constructor(
    @Inject('AUTH_CLIENT')
    private readonly client: ClientProxy,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();

    try {
      const res = await this.client
        .send(
          { role: 'auth', cmd: 'check' },
          { jwt: req.headers['authorization']?.split(' ')[1] },
        )
        .toPromise<boolean>();

      return res;
    } catch (err) {
      Logger.error(err);
      return false;
    }
  }
}

The controller:

  @UseGuards(JwtAuthGuard)
  @Get('greet')
  async greet(@Request() req): Promise<string> {
    return 'AUTHENTICATED!' + req;
  }

The response:

AUTHENTICATED![object Object]

Upvotes: 1

Views: 3830

Answers (1)

Abbah
Abbah

Reputation: 131

Attach the userId that you get in the AuthGuard to the req object and then you can access it in the controller:

// after fetching the auth user in the AuthGuard, attach its ID like this
req.userId = authUser.id

And in the controller, you can access it like this:

@UseGuards(JwtAuthGuard)
@Get('greet')
async greet(@Request() req): Promise<string> {
  return 'AUTHENTICATED USER ID!' + req.userId;
}

Upvotes: 5

Related Questions