javascript - JwtModule.registerAsync 在 NestJS 中不起作用
问题描述
我正在开发一个 NestJS 项目,我需要将 JWT 与.env
配置一起使用。它生成令牌,但在尝试访问安全 url(带有授权标头)时,它只返回未经授权的消息。
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 {}
主要的.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();
您会看到 my.env
位于项目的根目录中。
解决方案
如果您使用配置模块,您可以执行以下操作:
JwtModule.registerAsync({
useFactory: (config: ConfigService) => {
return {
secret: config.get<string>('JWT_SECRET_KEY'),
signOptions: {
expiresIn: config.get<string | number>('JWT_EXPIRATION_TIME'),
},
};
},
inject: [ConfigService],
}),
我也有初始化问题JwtModule
,这段代码解决了它。
推荐阅读
- git - 即使我没有本地更改,git pull 也会创建合并提交
- django - 模拟 pymongo 进行单元测试
- mysql - 为 1 列获取 1 个值
- angular5 - 在 Angular 5 中自定义 routerLink
- wpf - WPF列表框排序不起作用
- android - 在 google play store 上更新应用程序时,我的共享首选项正在删除
- git - 如何使用 rebase 正确反映从分支到另一个分支的更改
- java - 如何在java中的txt文件中写入特定数量的字符
- java - 使用 java priorityQueue 删除方法
- android - Android AWS sdk 无法上传