我是打字稿新手,正在尝试移植快速应用程序以使用打字稿。服务器使用 JWT 进行身份验证/授权,我有一个实用程序函数可以解码和验证给定的令牌。该函数被包装在一个承诺中,因此我可以在实现它的中间件中使用 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, ACCESS_TOKEN_SECRET as string, (err, payload: MyJwtPayload) => {
Thanks.