如何从@types/jsonwebtoken 向 JwtPayload 类型添加其他属性

问题描述

我是打字稿的新手,正在尝试移植一个 express 应用程序来使用打字稿。服务器使用 JWT 进行身份验证/授权,我有一个实用程序函数来解码和验证给定的令牌。该函数包含在一个 promise 中,因此我可以在实现它的中间件中使用 async/await。

import httpError from 'http-errors';
import jwt from 'jsonwebtoken';

const { ACCESS_TOKEN_SECRET } = process.env;

export function verifyAccessToken(token: string): Promise<jwt.JwtPayload | undefined> {
  return new Promise((resolve,reject) => {
    jwt.verify(token,ACCESS_TOKEN_SECRET as string,(err,payload) => {
      if (err) {
        return reject(new httpError.Unauthorized());
      }
      return resolve(payload);
    });
  });
}

此功能工作正常,但我在 JWT 中有其他信息。具体来说,我有一个 role 属性,因此有效负载的类型为:

{
  sub: string,// ID issued by mongoose
  role: string,// My new information that is causing error
  iat: number,exp: number
}

我的问题是来自@types/jsonwebtoken 的 JwtPayload 类型不包含 role,因此当 Promise 解决时,我在尝试访问身份验证中间件中的 payload.role 时收到打字稿错误。

import { RequestHandler } from 'express';
import httpError from 'http-errors';
import { verifyAccessToken } from '../utils'

export const authenticate: RequestHandler = async (req,res,next) => {
  try {
    const authHeader = req.headers['authorization'] as string;
    if (!authHeader) {
      throw new httpError.Unauthorized();
    }

    const accessToken = authHeader.split(' ')[1];
    if (!accessToken) throw new httpError.Unauthorized();

    const payload = await verifyAccessToken(accessToken);
// If I try to access payload.role here I get an error that type JwtPayload does not contain 'role'

    next();
  } catch (err) {
    next(err);
  }
};

如何扩展 JwtPayload 类型以添加​​角色属性?我尝试定义自己的自定义类型并完全覆盖从 jwt.verify() 返回的类型,但这会引发错误,表明没有重载与此调用匹配。

interface MyJwtPayload {
  sub: string;
  role: string;
  iat: number;
  exp: number;
}

// ... then in the utility function replace jwt.verify() call with
jwt.verify(token,payload: MyJwtPayload) => {

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)