我正在尝试使用nestjs文档实现身份验证。https://docs.nestjs.com/techniques/authentication
我正在实现JWT身份验证,在尝试访问经过身份验证的API时,即使在验证之前,我也会得到验证错误。有没有人遇到过类似的问题。
@Get()
@UseGuards(AuthGuard('jwt'))
async findAll(): Promise<UserDto[]> {
return this.userService.findAll();
}
这条路给了我UnAuthorized错误。我对打字稿和网易都很陌生。
我的代码可以在我的GitHub回购中获得。请告诉我出了什么问题。Project/blob/master/src/user/user.controller.ts#L23
发布于 2018-05-24 16:10:06
您的-轻微但关键的错误驻留在用于签名令牌的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 /!\
}
最后,要设置环境变量,请根据您的操作系统执行以下命令:
export SECRET=<your-secret-key>
set SECRET=<your-secret-key>
我希望它有帮助;)
发布于 2018-05-24 02:59:52
你是怎么进入这条路线的?
您必须先创建令牌。
不知道这是否给了你一个提示
https://stackoverflow.com/questions/50488975
复制相似问题