我陷入了同样的问题。这是我的代码(工作)供您比较:
src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { UserModule } from 'src/user/user.module';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: '1d',
},
}),
UserModule,
],
providers: [AuthService, JwtStrategy],
exports: [PassportModule, AuthService],
})
export class AuthModule {}
src/auth/auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { UserService } from 'src/user/user.service';
@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
private readonly userService: UserService,
) {}
makeToken(payload: JwtPayload) {
const { email } = payload;
return this.jwtService.sign({ email });
}
checkToken(token: string) {
return this.jwtService.verify(token);
}
async validateUser(payload: JwtPayload) {
return await this.userService.read(payload.email);
}
}
src/auth/jwt.strategy.ts
import { Strategy, ExtractJwt, VerifiedCallback } from 'passport-jwt';
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtPayload } from './interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}
async validate(payload: JwtPayload, done: VerifiedCallback) {
const user = await this.authService.validateUser(payload);
if (!user) {
done(new UnauthorizedException(), false);
}
return done(null, user);
}
}
src/auth/interfaces/jwt-payload.interface.ts
export interface JwtPayload {
email: string;
}
src/account/account.module.ts
import { Module } from '@nestjs/common';
import { AccountController } from './account.controller';
import { PassportModule } from '@nestjs/passport';
import { AuthModule } from 'src/auth/auth.module';
@Module({
imports: [AuthModule],
controllers: [AccountController],
})
export class AccountModule {}
src/account/account.controller.ts
import { Controller, UseGuards, Post } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('account')
export class AccountController {
@Post('skills')
@UseGuards(AuthGuard())
updateSkills() {
return console.log('something');
}
}
PS:我没有做 JwtAuthGuard。
我希望它对你有帮助:)