Home > OS >  How to use chain of jwt strategies in NestJS?
How to use chain of jwt strategies in NestJS?

Time:06-17

In my nestjs project, I am trying to use multiple jwt strategies. Here is the jwt-auth.guard.ts:

export class JwtAuthGuard extends AuthGuard(['jwt', 'sec']) {}

jwt.strategy.ts:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: ‘test’,
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}

sec.strategy.ts:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategysec extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: '1test',
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}

Auth.module.ts:

@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: 'test',
      signOptions: { expiresIn: '2000000s' },
    }),
  ],
  providers: [
    AuthService,
    LocalStrategy,
    JwtStrategysec,
    JwtStrategy,
  ],
  exports: [AuthService, JwtModule],
})
export class AuthModule {}

When I trying to use JwtAuthGuard in my code :

  @UseGuards(JwtAuthGuard)

I can get the error:

 ERROR [ExceptionsHandler] Unknown authentication strategy "sec"

Am I missing something here?

CodePudding user response:

In your sec.strategy.ts you need to give the strategy a custom name like so:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategysec extends PassportStrategy(Strategy, 'sec') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: '1test',
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}

otherwise it will take on the default 'jwt' name. With the above, it'll now have the name 'sec' and be properly registered with passport

  • Related