我有一个使用 jwt 实现身份验证的 NestJS(版本 6)项目。以下配置运行良好:
package.json
...
“@nest-modules/mailer”: “^1.1.3",
“@nestjs/common”: “^6.6.7",
“@nestjs/core”: “^6.6.7",
“@nestjs/jwt”: “^6.1.1",
“@nestjs/passport”: “^6.1.0",
“@nestjs/platform-express”: “^6.6.7",
...
jwt strategy file
@Injectable()
export class JwtBearerStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly sessionService: SessionService,
private readonly userRepository: UsersRepository
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: SESSION_SECRET_KEY
});
}
public async validate(session: Session) {
const user = await this.userRepository.findByUsername(session.user.username);
if (!user) {
throw new UnauthorizedException();
}
delete user.password;
return user;
}
}
End points are protected as follows
@Controller('/session')
export class SessionController {
constructor(
private readonly sessionService: SessionService,
private readonly userRepository: UsersRepository
) {}
@Get()
@UseGuards(AuthGuard())
public async getCurrentUser(@CurrentUser() currentUser: User) {
return currentUser;
}
但是,由于我更新了 nestJs 核心和通用模块,我无法提取身份验证。我的@CurrentUser
装饰器在请求中找不到用户对象。巢模块已更新为以下内容:
...
"@nestjs/common": "^7.6.15",
"@nestjs/core": "^7.6.15",
"@nestjs/jwt": "^7.2.0",
"@nestjs/microservices": "^7.6.15",
"@nestjs/passport": "^7.1.5",
"@nestjs/platform-express": "^7.6.15",
...
现在我的@UseGuards
装饰器抛出了这个自定义错误:
[CurrentUser Decorator]: No user found on request
No user objet found on request
* Please ensure Passport Module is configured correctly
* Ensure that the controller, or method is using @UseGuards(AuthGuard())
** see docs/auth.md for more informaion **
看来 AuthGuard 在版本 7 中的工作方式略有不同。还有其他人遇到过这个问题并且能够帮助我吗?