如何在Nodejs中使用JWT

星期日, 1月 7, 2024 | 2分钟阅读 | 更新于 星期日, 1月 7, 2024

@
如何在Nodejs中使用JWT

jsonwebtoken是一个npm包,提供了关于jsonwebtoken的生成、检查方法。

安装

npm install jsonwebtoken

生成token

返回一个token字符串

import jwt from "jsonwebtoken";
//语法:
export function sign(
    payload: string | Buffer | object,
    secretOrPrivateKey: Secret,
    options?: SignOptions,
): string;

jwt.sign(
    jsObject,
    privateKey,//密钥,可选。可为任意字符串
    { expiresIn: secondsalgorithm:"RS256" }
    //expiresIn 表示token的过期时间,数字表示秒数,字符串则有其他用法
);
//返回示例:
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoxNzA0NDU1MTg1NzE2LCJ0eXBlIjoidGVzdCIsImlhdCI6MTcwNDQ1NTE4NSwiZXhwIjoxNzA0NDU4Nzg1fQ.EGWRaDvmNxkzaUT8FJ1Me-xEEWwkycT3WEzx6O09UBY

注意事项:在签写token时,payload尽量使用object类型的,否则的话设置过期时间时会抛出错误,应该是个bug,没有理由string形式的payload不支持设置过期时间这一基本属性

检验token

export function verify(
    token: string,
    secretOrPublicKey: Secret,
    options?: VerifyOptions & { complete?: false },
): JwtPayload | string;
const decode_data = jwt.verify(token, privateKey);
//返回示例:
//{ iat,exp,...payload }

verify方法会检查token的有效性,有效则返回一个拷贝了原始对象属性、包含了iatexp属性的新对象:

  • iat表示token的生成时间戳(1970年来的秒 数)
  • exp表示token的实效时间戳(1970年来的秒数)。

无效则会抛出错误,因此需要增加try、catch来捕获错误:

try{
    jwt.verify(token,privateKey)
}catch(e){
    
}

其他设置

还可以设置audience属性来标记不同的token,在options对象传入字段:audience。 在verify时增加audioence属性来校验。 具体签写的options接口和验证的options接口如下:

export interface SignOptions {
    /**
     * Signature algorithm. Could be one of these values :
     * - HS256:    HMAC using SHA-256 hash algorithm (default)
     * - HS384:    HMAC using SHA-384 hash algorithm
     * - HS512:    HMAC using SHA-512 hash algorithm
     * - RS256:    RSASSA using SHA-256 hash algorithm
     * - RS384:    RSASSA using SHA-384 hash algorithm
     * - RS512:    RSASSA using SHA-512 hash algorithm
     * - ES256:    ECDSA using P-256 curve and SHA-256 hash algorithm
     * - ES384:    ECDSA using P-384 curve and SHA-384 hash algorithm
     * - ES512:    ECDSA using P-521 curve and SHA-512 hash algorithm
     * - none:     No digital signature or MAC value included
     */
    algorithm?: Algorithm | undefined;
    keyid?: string | undefined;
    /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js).  Eg: 60, "2 days", "10h", "7d" */
    expiresIn?: string | number | undefined;
    /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js).  Eg: 60, "2 days", "10h", "7d" */
    notBefore?: string | number | undefined;
    audience?: string | string[] | undefined;
    subject?: string | undefined;
    issuer?: string | undefined;
    jwtid?: string | undefined;
    mutatePayload?: boolean | undefined;
    noTimestamp?: boolean | undefined;
    header?: JwtHeader | undefined;
    encoding?: string | undefined;
    allowInsecureKeySizes?: boolean | undefined;
    allowInvalidAsymmetricKeyTypes?: boolean | undefined;
}
export interface VerifyOptions {
    algorithms?: Algorithm[] | undefined;
    audience?: string | RegExp | Array<string | RegExp> | undefined;
    clockTimestamp?: number | undefined;
    clockTolerance?: number | undefined;
    /** return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. */
    complete?: boolean | undefined;
    issuer?: string | string[] | undefined;
    ignoreExpiration?: boolean | undefined;
    ignoreNotBefore?: boolean | undefined;
    jwtid?: string | undefined;
    /**
     * If you want to check `nonce` claim, provide a string value here.
     * It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes))
     */
    nonce?: string | undefined;
    subject?: string | undefined;
    maxAge?: string | number | undefined;
    allowInvalidAsymmetricKeyTypes?: boolean | undefined;
}

© 2016 - 2025 Jebben 开发日志&网络随笔

🌱 Powered by Hugo with theme Dream.

关于博主

自我介绍

大家好,我是 Jabin,一名拥有 8 年工作经验的前端工程师。我是一个自学成才的开发者,通过不断学习和实践,积累了丰富的 web 端开发经验以及在 B 端后台管理、监控和 C 端教育、媒体类项目方面的丰富经验。

关于我的技能

我精通多种前端技术,包括但不限于:

  • JavaScript 和 TypeScript:我熟练掌握 JavaScript 和 TypeScript,能够利用它们构建出色的前端应用程序。
  • CSS:我对 CSS 有深入的理解,能够编写出美观、响应式的样式。
  • 前端框架:我熟练使用 Angular、React、Vue 和 Next.js 等前端框架,能够根据项目需求灵活选择并应用合适的技术栈。
  • 前端工具:我熟悉 webpack、Vite 等常用的前端打包工具,以及框架配套的 CLI 工具,能够高效地进行项目开发和部署。
  • 后端技术:我了解服务端语言 Java 和 Node.js,并能够与后端开发人员紧密合作,实现完整的应用程序。
  • 数据库和操作系统:我熟悉 SQL 数据库和 Linux 操作系统的常见操作和命令,能够进行数据库管理和服务器配置。

我的项目经验

我曾主导多个从零到一的项目,参与过数百万 UV 项目的开发,具有丰富的项目开发与团队合作经验。

我对技术充满热情,喜欢钻研新技术和解决复杂的技术问题。我还积极参与开源社区,贡献自己的力量,与各地的开发者共同探索和分享技术前沿。

结语

我是一个对技术认真负责、可靠可靠的人,热爱挑战和创新。我希望通过我的个人网站,与更多志同道合的人分享我的经验和见解,共同推动前端技术的发展和进步。

欢迎来到我的个人网站,期待与您的交流和合作!