AuthGuard broken after NestJS Update

275 views Asked by At

I have a NestJS (version 6) project that implemented authentication using jwt. The following config worked fine:

package.json
... 
“@nest-modules/mailer”: “^1.1.3",
“@nestjs/common”: “^6.6.7",
“@nestjs/core”: “^6.6.7",
“@nestjs/jwt”: “^6.1.1",
“@nestjs/passport”: “^6.1.0",
“@nestjs/platform-express”: “^6.6.7",
...

jwt strategy file

@Injectable()
export class JwtBearerStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly sessionService: SessionService,
    private readonly userRepository: UsersRepository
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: SESSION_SECRET_KEY
    });
  }

  public async validate(session: Session) {
    const user = await this.userRepository.findByUsername(session.user.username);
    if (!user) {
      throw new UnauthorizedException();
    }
    delete user.password;
    return user;
  }
}

End points are protected as follows
@Controller('/session')
export class SessionController {
  constructor(
    private readonly sessionService: SessionService,
    private readonly userRepository: UsersRepository
  ) {}

  @Get()
  @UseGuards(AuthGuard())
  public async getCurrentUser(@CurrentUser() currentUser: User) {
    return currentUser;
  }

However, since I updated nestJs core and common modules, I am unable to extract the authenticate. My @CurrentUser decorator cannot find the user object on the request. The nest modules have been updated to the following:

...
"@nestjs/common": "^7.6.15",
"@nestjs/core": "^7.6.15",
"@nestjs/jwt": "^7.2.0",
"@nestjs/microservices": "^7.6.15",
"@nestjs/passport": "^7.1.5",
"@nestjs/platform-express": "^7.6.15",
 ...

And now my @UseGuards decorator throws this custom error:

[CurrentUser Decorator]: No user found on request
  No user objet found on request
   * Please ensure Passport Module is configured correctly
   * Ensure that the controller, or method is using @UseGuards(AuthGuard())
  ** see docs/auth.md for more informaion **

It appears AuthGuard works slightly differently in version 7. Has anyone else had this issue and is able to help me?

0

There are 0 answers