Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why nestjs service is not injected into passport strategy?

I'm trying to make application using nestjs

Dependency injection into controller works well so far.

But when I inject service into passport strategy, injecting is not working.

I want to inject authService into googleStrategy.

This is my module code.

auth.modules.ts

@Module({
  imports: [
    UsersModules,
    PassportModule,
  ],
  controllers: [AuthController],
  providers: [AuthService, GoogleStrategy],
})
export class AuthModules {}

google.strategy.ts

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private authService: AuthService) {
    super({ /*...*/ });
    console.log(this.authService) //undefined
  }
}

In this case, AuthService is not injected.

When I inject AuthService manually using @Inject decorator, AuthService injected successfully.

constructor(@Inject('AuthService') private authService: AuthService) {
  super({ /*...*/ });
  console.log(this.authService) // AuthService is injected
}

Why service is not injected into passport strategy?

like image 301
wonderkids Avatar asked Oct 19 '25 10:10

wonderkids


1 Answers

i think that you want to do something like this

import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { config } from 'dotenv';
import { UserService } from 'src/user/user.service';
import { Injectable } from '@nestjs/common';
config();
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private readonly UserSerive: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.jwt_secret,
    });
  }

  async validate(payload: any) {
    return {
      user: payload.sub,
      username: payload.username,
      id: payload.id,
      roles: (await this.UserSerive.findOne(payload.id)).roles,
    };
  }
}
like image 127
mouawia_shride Avatar answered Oct 22 '25 07:10

mouawia_shride



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!