#APP_GUARD JWT passport strategy fails when having another Request Scoped Object

1 messages · Page 1 of 1 (latest)

honest gyro
#

we are building a multi-tenant application using NestJS and we have faced what i think is a common issue since the underlying problem have been posted in this github issue
https://github.com/nestjs/nest/issues/1870

the application throws the following Error at runtime and to be specific when calling a rest API
Error: Unknown authentication strategy "jwt"
we have created this MongooseConfigService that configures mongoose with specific tenant database on every call


@Injectable({ scope: Scope.DEFAULT })
export class MongooseConfigService implements MongooseOptionsFactory {
  
  private  mongooseConnectionManager: MongooseConnectionManager
  constructor(
    @Inject(REQUEST) private readonly request: IRequest,
  ) {
    this.mongooseConnectionManager = MongooseConnectionManager.getInstance()
  }

  createMongooseOptions(): MongooseModuleOptions {
    const tenantInfo = this.request.tenantInfo;
    let connection:mongoose.Connection = undefined;
    let uri:string = undefined
    if(tenantInfo.tenantId){
      uri = `...`;
      connection = this.mongooseConnectionManager.getTenantConnection(tenantInfo.tenantId, uri);
    }else{
      uri = `...`;
      connection = this.mongooseConnectionManager.getGlobalConnection(uri);
    }

    return {
      uri,
      connectionFactory: () => connection,
    };
   
  }
}

this works well until we integrate JWT authentication using passport


@Module({
  imports: [
  EventEmitterModule.forRoot(),
  ConfigModule.forRoot({
    isGlobal:true,
    load:[Configuration]
  }),
  MongooseModule.forRootAsync({
    useClass: MongooseConfigService,
  }),
  UsersModule,
  AuthModule,
  TenantModule
  ],
  providers:[
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard
    }
  ]
})
export class AppModule {}

Any help would be highly appreciated

GitHub

I'm submitting a... [ ] Regression [X] Bug report [ ] Feature request [ ] Documentation issue or request [ ] Support request => Please do not submit support request here, instead post your q...

leaden plaza
#

Passport strategies do not work with request scoped providers. That's a known limitation.

#

There's a workaround using moduleRef to resolve a request-scoped provider inside a singleton strategy.

#

Or check out the nestjs-cls library, which can help wjth multitenant stuff without using request scope (async local storage recipe in the docs)

honest gyro
#

@leaden plaza thnx for the help any references i can check for the first approach

leaden plaza