NestJs JWT身份验证返回401 [英] NestJs JWT Authentication returns 401
本文介绍了NestJs JWT身份验证返回401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在nestJs中实现了jwt身份验证.但是,每当我尝试使用以下授权标头进行身份验证时:
I have implemented a jwt authentication in nestJs. However whenever I attempt to authenticate using the following authorization headers:
Bearer <token> or JWT <token>
我收到401.这是我的身份验证文件
I got 401. These are my authentication files
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: `${process.env.SECRET}`,
});
}
async validate(payload: Credentials) {
const user: Account = await this.authService.validateAccount(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
handleRequest(err, user, info) {
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}
这是我的身份验证模块
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: `${process.env.SECRET}`,
}),
AccountModule,
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [PassportModule, AuthService],
})
export class AuthModule {
}
推荐答案
validate
仅在传递有效的jwt令牌时才被调用.当令牌使用其他机密签名或过期时,将永远不会调用validate
.确保您具有有效的令牌.您可以使用 jwt调试器来检查令牌.
validate
will only be called when you pass a valid jwt token. When the token is signed with a different secret or is expired, validate
will never be called. Make sure you have a valid token. You can check your token for example with the jwt debugger.
这篇关于NestJs JWT身份验证返回401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文