我正在尝试使用 nestjs 文档实现身份验证。https://docs.nestjs.com/techniques/authentication
我正在实施 JWT 身份验证,当尝试访问正在验证的 API 时,即使在验证之前,我也收到验证错误。有没有人遇到过类似的问题。
@Get()
@UseGuards(AuthGuard('jwt'))
async findAll(): Promise<UserDto[]> {
return this.userService.findAll();
}
这条路线给了我 UnAuthorized 错误。我对 Typescript 和 nestjs 真的很陌生
我的代码在我的 GitHub 存储库中可用。请让我知道出了什么问题。https://github.com/shamnadps/TypeScript_Project/blob/master/src/user/user.controller.ts#L23
您 - 轻微但严重的 - 错误存在于secretOrKey
您用于签署令牌的值中。src/auth/jwt.strategy.ts
和之间有不同的值src/auth/auth.service.ts
。
在src/auth/auth.service.ts
:
而不是这个:
async createToken() {
const user: UserDto = { name: 'shamnad', phoneNumber: '12435' };
return jwt.sign(user, 'secretkey'); // <== /!\ focus on this one /!\
}
用这个:
async createToken() {
const user: UserDto = { name: 'shamnad', phoneNumber: '12435' };
return jwt.sign(user, 'secretKey'); // <== /!\ focus on this one /!\
}
因为你secretKey
用来签署你的令牌,而不是secretkey
(注意骆驼案例):
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey', // <== /!\ focus on this line /!\
});
}
为避免此类问题,我建议您使用process.env.<your-variable>
而不是直接在字符串中手动设置配置。
它看起来像这样src/auth/jwt.strategy.ts
:
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.SECRET
});
}
并在src/auth/auth.service.ts
,像这样:
async createToken() {
const user: UserDto = { name: 'shamnad', phoneNumber: '12435' };
return jwt.sign(user, process.env.SECRET); // <== /!\ focus on this one /!\
}
最后,要设置环境变量,请根据您的操作系统执行以下命令:
- Mac OS:export SECRET=<your-secret-key>
- Windows:set SECRET=<your-secret-key>
我希望它有帮助;)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句