I\'m failed to compile with this error:
Nest can\'t resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument at index [0] is available
You can make a separate module for it (SharedModule)
make sure you have the following packages installed
npm i --save @nestjs/jwt
npm i --save @nestjs/passport
(optional, if you go with MongoDB/Mongoose)
npm i --save @nestjs/mongoose
shared.module.ts
@NgModule({
imports: [
PassportModule.register({
defaultStrategy: 'jwt',
}),
JwtModule.register({
secret: process.env.JWT_SECRET_KEY,
signOptions: {
expiresIn: '2 days',
},
}),
],
providers: [JwtStrategy],
exports: [JwtStrategy, PassportModule]
})
jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(@InjectModel('User') private collection: Model) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET_KEY,
});
}
async validate(payload: JwtPayload): Promise {
const { username } = payload;
const user = await this.collection.findOne({ username });
if (!user) {
throw new UnauthorizedException('JwtStrategy unauthorized');
}
return user;
}
}
Now where you want to use it, just import in your module SharedModule. In your controllers use the following decorator
@UseGuards(AuthGuard())