0

I can not get a token.I am using import { JwtService } from '@nestjs/jwt';.The package version is "@nestjs/jwt": "^9.0.0".The this.jwtService.sign(payload) function takes only one parameter. It shows error that I have been giving below.

Error: secretOrPrivateKey must have a value
    at Object.module.exports [as sign] (D:\nextjs-projects\shopping-app\server_v2\node_modules\jsonwebtoken\sign.js:107:20)    at JwtService.sign (D:\nextjs-projects\shopping-app\server_v2\node_modules\@nestjs\jwt\dist\jwt.service.js:28:20)      
    at AuthService.login (D:\nextjs-projects\shopping-app\server_v2\src\auth\auth.service.ts:28:35)
    at AppController.login (D:\nextjs-projects\shopping-app\server_v2\src\app.controller.ts:16:35)
    at D:\nextjs-projects\shopping-app\server_v2\node_modules\@nestjs\core\router\router-execution-context.js:38:29        
    at D:\nextjs-projects\shopping-app\server_v2\node_modules\@nestjs\core\router\router-execution-context.js:46:28        
    at D:\nextjs-projects\shopping-app\server_v2\node_modules\@nestjs\core\router\router-proxy.js:9:17

My Code: 1.AuthModule code is given bellow:

@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: 'ndUdggLVxTccGBJmr1BoFvAQnSEt+Osx5pgdGTOL9XwajAn4fe40Q41NbBTa9wNekjKuTLdhWBJQhi71JShvi7rFoayh3QIuEA3e4Eq8mU7lwArngzFWdSiIJgMplTLboFOeR7q8pv7MoDcl2dBmuZI4NQ5GglznC8Ebl20Sa41cg4EDkuppblXa+bqvZeSQRg0d/AL9f8NIBC3N6sEyc1nM0MWeWc1CxKuljTVQm1g2RVLG1cSNU/a5vpmy/9UwYiDiIr2aCbD60EWkQMR2vDvW/0LsVun72xEqUTdY5UuczofpmhtCxm+yw9R7iFsNcNuJAyAQN0T9OtMyt9wzPA==',
      signOptions: { expiresIn: '1h' },
    }),
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  providers: [AuthService, LocalStrategy],
  exports: [AuthService],
})
export class AuthModule {}

2.AuthService code is given bellow:

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
  ) {}

  async login(user: any) {
    const payload = {
      name: user.email,
      sub: user.phone,
    };
    const token = this.jwtService.sign(payload);
    return {
      accessToken: token,
    };
  }
}

3.AppModule code is given bellow:

@Module({
  imports: [
    AuthModule,
    UsersModule,
    MongooseModule.forRoot(
      `mongodb+srv://${dbConstant.username}:${dbConstant.password}@cluster0.34saife.mongodb.net/users?retryWrites=true&w=majority`,
    ),
  ],
  controllers: [AppController],
  providers: [AppService, AuthService, JwtService],
})
export class AppModule {}

4.AppController code is given bellow:

export class AppController {
  constructor(
    private readonly authService: AuthService,
  ) {}

  @UseGuards(AuthGuard('local'))
  @Post('auth/login')
  async login(@Request() req: any) {
    return await this.authService.login(req.user);
  }
}
Md.Shakil Shaikh
  • 347
  • 4
  • 11

2 Answers2

1

You need to add JwtSignOptions as second parameter

async login(user: any) {
        const payload = {
          name: user.email,
          sub: user.phone,
        };
        const token = this.jwtService.sign(payload,{secret: "youSecretKey" });
        return {
          accessToken: token,
        };
}
0

If you want to re-use the same AuthService and JwtService from the AuthModule where you originally configure the JwtModule, you need to remove the AuthService and JwtService from the AppModule's providers and only have the AuthModule in the AppModule's imports. This will ensure that only one AuthService instance is created and used (the one in the AuthModule's providers and exports).

The reason for your error is that you declare that you need a new JwtService via adding it to the AppModule's providers, and the dependencies of JwtService, the options it uses, are optional, so there's no error on startup.


TL;DR: make your AppModule look like this

@Module({
  imports: [
    AuthModule,
    UsersModule,
    MongooseModule.forRoot(
      `mongodb+srv://${dbConstant.username}:${dbConstant.password}@cluster0.34saife.mongodb.net/users?retryWrites=true&w=majority`,
    ),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147