NestJs JWT身份验证返回401

编程入门 行业动态 更新时间:2024-10-26 09:35:09
本文介绍了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

本文发布于:2023-11-26 16:43:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   NestJs   JWT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!