JwtModule.registerAsync在NestJS中不起作用

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

我正在开发一个NestJS项目,我需要使用JWT和.env配置。它生成令牌,但在尝试访问安全URL时(使用Authorization标头),它只返回Unauthorized消息。

jwt.strategy.ts

import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { JwtPayload } from './interfaces/jwt-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

    constructor(private readonly authService: AuthService) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: process.env.JWT_SECRET_KEY,
        });
    }

    async validate(payload: JwtPayload) {
        const user = await this.authService.validateUser(payload);
        if (!user) {
            throw new UnauthorizedException();
        }

        return user;
    }
}

auth.module.ts

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      useFactory: async () => ({
        secretOrPrivateKey: process.env.JWT_SECRET_KEY,
        signOptions: {
          expiresIn: process.env.JWT_EXPIRATION_TIME,
        },
      }),
    }),
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
})
export class AuthModule {}

main.ts

import { NestFactory } from '@nestjs/core';
import * as dotenv from 'dotenv';
import { ApiModule } from './api/api.module';
import { Logger } from '@nestjs/common';

async function bootstrap() {
  dotenv.config({ path: './.env'});
  const app = await NestFactory.create(ApiModule);
  const port = process.env.APP_PORT;

  await app.listen(port);
  Logger.log(`Server started on http://localhost:${port}`);
}
bootstrap();

看起来JwtModule.registerAsync不使用环境变量。我尝试了很多东西,但它总是失败。如果我在auth.module.ts中为静态数据更改环境变量,那么它可以正常工作。像这样的东西:

secretOrPrivateKey: 'secretKey',
signOptions: {
  expiresIn: 3600,
},

更新项目结构

- src
    - api
        - auth
            - interfaces
                jwt-payload.interface.ts
            auth.controller.ts
            auth.module.ts
            auth.service.ts
            jwt.strategy.ts
            index.ts
        api.module.ts
        index.ts
    main.ts
- test
.env

我的main.ts现在看起来像这样。

import { NestFactory } from '@nestjs/core';
import * as dotenv from 'dotenv';
import { resolve } from 'path';
import { ApiModule } from './api/api.module';
import { Logger } from '@nestjs/common';

async function bootstrap() {
  dotenv.config({ path: resolve(__dirname, '../.env') });
  const app = await NestFactory.create(ApiModule);
  const port = process.env.APP_PORT;

  await app.listen(port);
  Logger.log(`Server started on http://localhost:${port}`);
}
bootstrap();

你看到我的.env是项目的根目录。

javascript node.js jwt nestjs dotenv
1个回答
0
投票

对我来说,你的代码有效:

Edit Nest.js JWT Auth

你的.env文件在哪里?您的配置dotenv.config({ path: './.env'});等于默认配置dotenv.config();,其中.env文件在项目根目录中查找(而不是在src中)。

如果要将.env文件放在src目录中,请使用以下配置

import { resolve } from 'path';
dotenv.config({ path: resolve(__dirname, '.env') });

我建议不要直接使用你的环境变量,而是将它们封装在ConfigService中,请参阅docs。这使得测试和重构更容易。

© www.soinside.com 2019 - 2024. All rights reserved.