Shewbii
Shewbii

Reputation: 55

NestJS / NodeJS / Passport / JWT - Stock current user

I have a NestJS backend, secured by JWT. I would like to know what is the best way to store the actual user or the best way to pass it to my services?

I have a JwtAuthGuard

@Injectable()
export class JwtAuthGuard extends AuthGuard( 'jwt' ) {
  canActivate(context: ExecutionContext) {
    return super.canActivate( context );
  }

  handleRequest(err, user, info) {
    if ( err || !user ) {
      throw err || new UnauthorizedException();
    }
    return user;
  }
}

My actual user id is in user var in handleRequest but I don't know where to "stock" it to be able to reach it in some modules. Does anyone can help me ?

Thanks

Upvotes: 1

Views: 11661

Answers (1)

Daniel
Daniel

Reputation: 2531

The JWT itself is where you store the user id (or any identifying details of the user).

If you create the JWT payload with the user id ({ id: 123, ... }) the passport will set the user member to the request object.

Important: Don't store sensitive data in the JWT.

  @AuthGuard( 'jwt' )
  @Get('profile')
  getUserId(@Request() req: any) {
    return req.user.id;
  }

You can pass the req.user.id to services as needed.

See: https://docs.nestjs.com/techniques/authentication#implement-protected-route-and-jwt-strategy-guards


One last thing: If you like to have types for the request object you can do something like this

import { Request as HttpRequest } from 'express';


interface UserJwtPayload {
  id: string,
}
type AuthRequest = HttpRequest & { user: UserJwtPayload }

Upvotes: 8

Related Questions