Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In nest.js while using passport module do we have to use PassportModule.register() inside each modules?

If we don't import them inside each modules using @AuthGuard decorator then it's showing the following warning in logs.

In order to use "defaultStrategy", please, ensure to import PassportModule in each place where AuthGuard() is being used. Otherwise, passport won't work correctly

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    UsersModule,
  ],
  providers: [AuthService, JwtStrategy],
})
export class AuthModule {}

Is there any other way besides importing "PassportModule.register({ defaultStrategy: 'jwt' })" inside each modules.

like image 536
Frozenex Avatar asked Nov 17 '18 17:11

Frozenex


People also ask

What is passport in NestJS?

Passport is the most popular node.js authentication library, well-known by the community and successfully used in many production applications. It's straightforward to integrate this library with a Nest application using the @nestjs/passport module.

What is JWT in NestJS?

JWT stands for JSON Web Tokens. Using JWT effectively can make our applications stateless from an authentication point of view. We will be using the NestJS JWT Authentication using Local Strategy as the base for this application.


1 Answers

Assuming that your other Modules are importing the AuthModule in order to have access to the AuthService you could just re-export the PassportModule:

const passportModule = PassportModule.register({ defaultStrategy: 'jwt' });

@Module({
  imports: [
    passportModule,
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    UsersModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [passportModule]
})
export class AuthModule {}
like image 127
Jesse Carter Avatar answered Dec 16 '22 16:12

Jesse Carter