阅读将在Nestjs的JWT护照中验证的访问令牌
我正在构建Nestjs后端API服务器,并且使用JWT通过护照策略来验证和验证用户请求。 我的问题:我想阅读JWT策略的验证功能中的访问令牌。 下图:我的代码的示例 注意:我的目标是解码访问令牌,并获取我使用的用户代理来生成额外验证层的令牌(以确保请求来自同一设备)。如果您有更好的方法,我很乐意知道它:)
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWTSecret,
});
}
async validate(payload: any) {
//I want to read the access token that would be validated here
return { userId: payload.sub, username: payload.username , useragent: payload.useragent};
}
}
I am building a nestjs back-end api server, and I'm using JWT to authenticate and validate user requests through passport strategies.
My question: I want to read the access token inside the validate function of JWT strategy.
Below: an example of my code
Note: my goal is to decode the access token and get the user agent I use to generate the token for an extra validation layer (to make sure the request is coming from the same device). If you have a better way, I would be happy to know it :)
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWTSecret,
});
}
async validate(payload: any) {
//I want to read the access token that would be validated here
return { userId: payload.sub, username: payload.username , useragent: payload.useragent};
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将请求转发到
validate
方法。You can forward the request to the
validate
method.事实证明,我没有在有效载荷中使用用户代理。
因此,要回答我自己的问题,就像@WS所说,您可以使用有效载荷查找所有有效载荷组件。
It turn out that I was not using the user agent in payload.
So to answer my own question and like @W.S said, you can use the payload to find all of the payload components.