[NestJs]:JwtModule.register() 不起作用

问题描述 投票:0回答:2

我在 NestJs 中使用 JwtModule,似乎注册方法没有为我注入的服务设置

secret
属性。 我收到此错误:enter image description here

这是代码:

  • 注册 JwtModule 的 Auth 模块:
@Module({
  imports: [
    UserModule,
    PassportModule,
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1w' },
    }),
  ],
  providers: [AuthService, BcryptService, LocalStrategy, JwtStrategy],
  controllers: [AuthController],
})
export class AuthModule {}
  • Auth 控制器,我在其中调用
    login()
    方法:
@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @UseGuards(LocalGuard)
  @Post('/login')
  async login(@Request() request) {
    return this.authService.login(request.user);
  }
}
  • 我调用的身份验证服务
    jwtService.sign()
@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly bcryptService: BcryptService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(email: string, password: string): Promise<User> {
    try {
      const user = await this.userService.findByEmail(email);
      await this.bcryptService.comparePassword(password, user.password);
      return user;
    } catch (err) {
      throw new HttpException(err.message, HttpStatus.UNAUTHORIZED);
    }
  }

  async login(user: User) {
    const payload = { userEmail: user.email, userId: user.id };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

事实上,我必须像这样将

options
对象添加到
jwtService.sign()
才能使其工作:

  async login(user: User) {
    const payload = { userEmail: user.email, userId: user.id };
    return {
      access_token: this.jwtService.sign(payload, {
        secret: process.env.JWT_SECRET,
      }),
    };

我正在寻找“为什么注册方法不起作用?”的解释, 我预计不必在

option
方法中添加
sign()
对象。

为什么?

如果没有设置秘密,是否设置了过期时间?

typescript jwt nestjs passport.js
2个回答
0
投票

抛出的错误是由于

process.env.JWT_SECRET
未定义,因此 auth 模块中的
secret
。 env 变量未定义的原因是由于应用程序中的环境配置设置所致。

要使此变量在 auth 模块中可访问,您应该在 auth 模块中动态导入

ConfigModule
或像这样全局定义它:

ConfigModule.forRoot({
  isGlobal: true,
});

一旦变量可访问,您就不必在

login
方法中显式定义它。是的,设置了过期时间,因为它与环境变量配置无关。


0
投票
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtModule } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';

@Module({
  imports: [
    JwtModule.registerAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        secret: configService.get<string>('JWT_SECRET'),
      })
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {
}

enter code here
© www.soinside.com 2019 - 2024. All rights reserved.