vue.js - 如何使用 'jsonwebtoken' 库在 Nuxt 3 中生成 JWT token ?

标签 vue.js jwt nuxtjs3 msw

我正在使用mswjs用于在 Nuxt 3 (3.0.0-rc.11) 项目中模拟 API 的库;一切工作正常,直到我尝试导入 ' jsonwebtoken ' 库来生成 JWT 访问 token 来模拟登录 API 调用。

这是登录请求处理程序:

//file path: @/mocks/auth.js
import {rest} from 'msw'
import { addBaseUrl, makeResponse } from './helpers'
import jwt from 'jsonwebtoken'

export default [
   rest.post(addBaseUrl('/api/auth/login/'), (req, res, ctx) => {
     const json = {
       access: jwt.sign(
         {test: 'test'},
         'secret',
         {expiresIn: 600}       )
     }
     return makeResponse({res, ctx, status: 200, delay: 1000, json})
  }),
]

问题是,当我尝试导入 jwt 时,它会抛出此错误,并且一切都会停止工作:

util.js:109 Uncaught TypeError: Cannot read properties of undefined (reading 'NODE_DEBUG')
    at node_modules/util/util.js (util.js:109:17)
    at __require (chunk-7NEK6ARH.js?v=bb8c835c:9:50)
    at node_modules/jws/lib/data-stream.js (data-stream.js:4:12)
    at __require (chunk-7NEK6ARH.js?v=bb8c835c:9:50)
    at node_modules/jws/lib/sign-stream.js (sign-stream.js:3:18)
    at __require (chunk-7NEK6ARH.js?v=bb8c835c:9:50)
    at node_modules/jws/index.js (index.js:2:18)
    at __require (chunk-7NEK6ARH.js?v=bb8c835c:9:50)
    at node_modules/jsonwebtoken/decode.js (decode.js:1:11)
    at __require (chunk-7NEK6ARH.js?v=bb8c835c:9:50)

该问题是由 jws 引起的库是 jsonwebtoken 库的依赖项。我不知道如何解决这个问题,我非常感谢任何帮助

这是我的 package.json 文件:

{
  "private": true,
  "scripts": {
    "start": "nuxt start",
    "build": "nuxt build",
    "dev": "nuxt dev --https --ssl-cert localhost.pem --ssl-key localhost-key.pem",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
  "devDependencies": {
    "@iconify/vue": "^4.0.0",
    "autoprefixer": "^10.4.8",
    "msw": "^0.47.3",
    "nuxt": "3.0.0-rc.11",
    "postcss": "^8.4.16",
    "tailwindcss": "^3.1.8"
  },
  "dependencies": {
    "@vue-leaflet/vue-leaflet": "^0.6.1",
    "@vuelidate/core": "^2.0.0-alpha.44",
    "@vuelidate/validators": "^2.0.0-alpha.31",
    "dayjs": "^1.11.5",
    "jsonwebtoken": "^8.5.1",
    "jwt-decode": "^3.1.2",
    "leaflet": "^1.9.1",
    "vue-google-charts": "^1.1.0",
    "vue3-carousel": "^0.1.46"
  },
  "packageManager": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c8d0c3dff1829f839f82" rel="noreferrer noopener nofollow">[email protected]</a>",
  "msw": {
    "workerDirectory": "public"
  }
}

最佳答案

jsonwebtoken似乎使用node-jws,我认为,它不会工作,因为mswjs(模拟服务 worker JS)在浏览器中运行并且因此不在节点上。

我目前正在寻找同一问题的解决方案,但我想继续使用 MSWjs 来模拟我的后端,同时创建有效的 JWT(在浏览器中,因为模拟服务工作线程脚本在浏览器,不在后端)。

我要尝试https://www.npmjs.com/package/jose与 MSWjs 结合使用。

编辑: 我已经尝试过,它似乎有效。

我已经在我的 browser.ts 中生成了一个用于验证的 publicKey 和一个用于签名 JWT 的 privateKey,如下所示:

export const { publicKey, privateKey } = await jose.generateKeyPair('ES256')

并在我的 auth-handlers.ts 中使用,我将其包含在 handlers.ts 中,如下所示:

import { privateKey } from './browser'
...
async function createJwt(foundUser: UserData | undefined): Promise<string> {
    return new jose.SignJWT({ 'urn:example:claim': true })
        .setProtectedHeader({ alg: 'ES256' })
        .setIssuedAt()
        .setIssuer('urn:example:issuer')
        .setAudience('urn:example:audience')
        .setExpirationTime('2h')
        .sign(privateKey)
}

保持 publicKey 对所有处理程序可用非常重要,因为您将使用它来验证在请求 header 中获得的 JWT,并且可能在需要时使用声明。

此外,我避免重定向到登录屏幕,而是将 {email: ..., password: ...} 正文作为 POST 请求发送到 /auth/login 以防在处理所谓 protected 端点时未找到 cookie。

实际上,您会将用户重定向到登录表单,并在完成后将用户重定向回我所理解的原始 URL。

最后,我使用 jose 生成并签署 JWT,并使用 ctx.cookie('Authorization) 将结果附加到 auth-handler 响应的 header ', '承载' + jwt)。因为它重定向回调用它的 URL (/api/user/login -> /api/auth/login -> cookie 附加到响应 -> /api/user/login),我能够处理登录并返回 Authorization: Bearer ... header ,然后我可以将其用于下一次调用。

我仍然需要弄清楚是否应该使用刷新 token 以及如何使用,但我希望这可以帮助您入门。

关于vue.js - 如何使用 'jsonwebtoken' 库在 Nuxt 3 中生成 JWT token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73957831/

相关文章:

javascript - 导出未在 ES 模块范围内定义

javascript - document.execCommand 不是 vue test utils 中的函数

javascript - Vue.js:仅当条件为真时才阻止表单提交

Javascript "includes"通过破折号分割数组中的项目(VueJS)

azure - 如何忽略 Azure API Manager validate-jwt 策略中的特定 URL

vuejs3 - 如何使用 useFetch 获取 Nuxt 3 中的错误响应正文?

docker - 无法访问使用 Nginx 服务 Dockerized VueJS 应用程序并导致 SSL 错误

security - 使用多种身份验证方法的 ASP.NET Core

http - 如何将自定义 HTTP 请求 header 添加到 Thymeleaf 生成的表单或链接?

docker - 使用 docker 运行 nuxt3