簡體   English   中英

如何從@types/jsonwebtoken 向 JwtPayload 類型添加其他屬性

[英]How to add additional properties to JwtPayload type from @types/jsonwebtoken

我是打字稿的新手,正在嘗試移植 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
}

我的問題是,從@類型/ jsonwebtoken不包含JwtPayload類型role ,因此當無極做出決議,我試圖訪問時收到錯誤打字稿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, ACCESS_TOKEN_SECRET as string, (err, payload: MyJwtPayload) => {

謝謝。

您應該能夠通過聲明合並來實現這一點。

在您的代碼中的某處添加以下內容:

declare module "jsonwebtoken" {
    export interface JwtPayload {
        role: string;
    }
}

這應該可以根據需要擴展接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM