我遇到了 Nestjs 的问题。 我已经这样定义了我的
auth.module.ts
:
import { Module } from '@nestjs/common';
import { UserModule } from 'src/user/user.module';
import { AuthController } from './auth.controller';
import { JwtModule } from '@nestjs/jwt';
@Module({
imports: [
UserModule,
JwtModule.register({
global: true,
secret: process.env.JWT_CONSTANT,
signOptions: { expiresIn: '1h' },
}),
],
providers: [],
controllers: [AuthController],
})
export class AuthModule {}
这是我的
auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from 'src/user/user.service';
@Injectable()
export class AuthService {
constructor(
private userService: UserService,
private jwtService: JwtService,
) {}
async signIn(
email: string,
userPassword: string,
): Promise<{ accessToken: string }> {
const user = await this.userService.getUser(email);
if (user.password !== userPassword) {
throw new UnauthorizedException();
}
const payload = { sub: user.id, username: user.pseudo };
return {
accessToken: await this.jwtService.signAsync(payload, {
secret: process.env.JWT_CONSTANT,
}),
};
}
}
只要我在身份验证服务中传递秘密,它就可以完美工作,但是通过遵循文档,我不必在此处传递它,因为我已经在模块中定义了它。我检查了是否有
process.env.JWT_CONSTANT
,但事实并非如此,我什至将其替换为硬编码字符串“toto”,但问题仍然存在。
最后,这是应用程序模块:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { AuthController } from './auth/auth.controller';
import { AuthService } from './auth/auth.service';
import { JwtService } from '@nestjs/jwt';
import { UserService } from './user/user.service';
import { PrismaService } from './prisma.service';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
],
controllers: [AppController, AuthController],
providers: [AppService, AuthService, UserService, JwtService, PrismaService],
})
export class AppModule {}
使用registerAsync
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get('JWT_CONSTANT'),
signOptions: {
expiresIn: '1h',
},
}),
})