Bra*_*den 10 types jwt typescript definitelytyped express-jwt
我是打字稿新手,正在尝试移植快速应用程序以使用打字稿。服务器使用 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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
这个函数工作正常,但是我在 JWT 中有更多信息。具体来说,我有一个role属性,因此有效负载的类型为:
{
sub: string, // ID issued by mongoose
role: string, // My new information that is causing error
iat: number,
exp: number
}
Run Code Online (Sandbox Code Playgroud)
我的问题是 @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);
}
};
Run Code Online (Sandbox Code Playgroud)
如何扩展 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) => {
Run Code Online (Sandbox Code Playgroud)
谢谢。
使用扩展的有效负载重新jsonwebtoken声明模块,然后相应地解析/转换经过验证的令牌。
import * as jwt from 'jsonwebtoken'
declare module 'jsonwebtoken' {
export interface UserIDJwtPayload extends jwt.JwtPayload {
userId: string
}
}
export const userIdFromJWT = (jwtToken: string): string | undefined => {
try {
const { userId } = <jwt.UserIDJwtPayload>jwt.verify(jwtToken, process.env.JWT_COOKIE_SECRET || 'MISSING_SECRET')
return userId
} catch (error) {
return undefined
}
}
Run Code Online (Sandbox Code Playgroud)
您应该能够通过声明合并来实现这一点。
在代码中的某处添加以下内容:
declare module "jsonwebtoken" {
export interface JwtPayload {
role: string;
}
}
Run Code Online (Sandbox Code Playgroud)
这应该可以根据需要扩展接口。
| 归档时间: |
|
| 查看次数: |
13376 次 |
| 最近记录: |