Que*_*n3r 0 javascript node.js jwt nestjs
据我所知,要使令牌无效,这是存储令牌的最佳方法,它是数据库的到期日期时间。要验证它,您只需从数据库中选择它,如果它存在,就知道它已失效。此外,您可以在数据库的过期日期时间之前删除每个过期的令牌。
因此,我创建了一个中间件,该中间件从授权标头中提取令牌,并将该令牌和到期日期时间附加到该request对象。signOut路由使令牌失效需要日期时间。
async use(req: any, res: Response, next: NextFunction) {
try {
const headers: IncomingHttpHeaders = req.headers;
const authorization: string = headers.authorization;
const bearerToken: string[] = authorization.split(' ');
const token: string = bearerToken[1];
if (await this.authenticationsRepository.findByEncodedToken(token)) { // invalidated token?
throw new Error(); // jump to catch
}
req.tokenPayload = verifyToken(token); // calls jwt.verify with secret
next();
} catch (error) {
throw new UnauthorizedException();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如何exp从令牌中提取属性以计算到期日期时间呢?
为了获得到期日期,您需要解码jsonwebtoken并访问它的exp密钥,就像这样:
let token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: '1h' });
var decoded = jwt.decode(token, { complete: true });
console.log(decoded.payload.exp);
Run Code Online (Sandbox Code Playgroud)
我认为您可以这样做:
req.expirationTime = jwt.decode(token, { complete: true }).payload.exp;
Run Code Online (Sandbox Code Playgroud)