Reputation:
As the title of the post says, I can't inject service in the following authguard class, I get an error each time I try to, the error happens in the JwtAccessTokenGuard where I try to inject the JwtTokenService to access some of the class method however it does not woks as expected :
@Injectable()
export class JwtAccessTokenGuard implements CanActivate {
constructor(
@Inject(JwtTokenService) private readonly jwtTokenService: JwtTokenService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) throw new UnauthorizedException();
try {
return true;
} catch {
throw new UnauthorizedException();
}
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
I already added global guard in app module:
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
AuthModule,
UserModule,
PrismaModule,
BcryptModule,
JwtTokenModule,
LibModule,
TwoFaModule,
],
providers: [
{
provide: APP_GUARD,
useClass: JwtAccessTokenGuard,
},
],
})
export class AppModule {}
Here is the User Module :
@Module({
controllers: [UserController, JwtTokenModule],
providers: [UserService, PrismaService],
exports: [UserService],
})
export class UserModule {}
and here is the Jwt Module :
import { Module } from '@nestjs/common';
import { JwtTokenService } from './jwtToken.service';
import { JwtModule } from '@nestjs/jwt';
@Module({
imports: [JwtModule],
providers: [JwtTokenService],
exports: [JwtTokenService],
})
export class JwtTokenModule {}
and this is the error returned by nestjs:
[Nest] 79549 - 09/28/2023, 12:35:42 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the JwtAccessTokenGuard (?). Please make sure that the argument JwtTokenService at index [0] is available in the UserModule context.
Potential solutions:
- Is UserModule a valid NestJS module?
- If JwtTokenService is a provider, is it part of the current UserModule?
- If JwtTokenService is exported from a separate @Module, is that module imported within UserModule?
@Module({
imports: [ /* the Module containing JwtTokenService */ ]
})
Error: Nest can't resolve dependencies of the JwtAccessTokenGuard (?). Please make sure that the argument JwtTokenService at index [0] is available in the UserModule context.
Upvotes: 1
Views: 200