How set more "jwt" AuthGuard in nestjs?

Viewed 269

i'm new to nestjs, i've already set a "jwt" PassportStrategy with his relative AuthGuard, now i have to create a complete different "jwt" PassportStrategy and his relative AuthGuard, how can i do this? Do you have any examples?

2 Answers

Firstly you create another strategy class. The second argument when extending the base PassportStrategy will be the name of your strategy which you can use with AuthGuard to specify which strategy it will use.

export class OtherStrategy extends PassportStrategy(Strategy, 'other-strategy')
{ STRATEGY IMPLEMENTATION }

Then you can use it in your controller like

@UseGuards(AuthGuard('other-strategy')
@Post('/my-endpoint')

Have you provided the jwt strategy in the auth module providers array?

Here is a sample file: auth.module.ts:

@Module({
  imports: [
    ConfigModule.forRoot(),
    UsersModule,
    PassportModule,
    JwtModule.register({
      privateKey: process.env.JWT_SECRET_KEY,
      signOptions: { expiresIn: '60s' },
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtStrategy],
})
export class AuthModule { }
Related