I'm using NestJS 10 with TypeORM 0.3.17. I have this method in my controller
@UseGuards(AccessTokenGuard)
@Post()
create(
@Req() req: Request,
@Body() createOrderDto: CreateOrderDto,
): Promise<Order> {
const userId = req.user['sub'];
return this.ordersService.create(userId, createOrderDto);
}
and this is how the guard is defined
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class AccessTokenGuard extends AuthGuard('jwt') {}
My question is, what if I want to unprotect the route (it is not required to submit a valid JWT token to access the route), but I would like to access the user if there is a valid JWT submitted. I'm noticing that if I remove the
@UseGuards(AccessTokenGuard)
line, I can't get access to the "req.user['sub']" object anymore.
req.useris populated by parsing theJWTthat is sent which is whatpassport-jwtis doing. If you don't call to theAccessTokenGuardthen the jwt is never parsed andreq.useris never populated. If you want, you can make anOptionalTokenGuardthat calls to thecanActivateofAuthGuard('jwt')but returnstrueregardless the outcome, so thatreq.usermight be populated. This would look something like