NodeJS 使用FastifyJWT通过查询参数发出验证令牌:TypeError - request.jwtVerify不是函数

monwx1rj  于 2023-11-17  发布在  Node.js
关注(0)|答案(1)|浏览(176)

当前的问题围绕着在Fastify应用程序中使用FastifyJWT进行令牌验证。具体来说,当尝试对通过GET请求中的查询参数接收的令牌执行验证过程时,函数request.jwtVerify(token)会产生错误“TypeError:request.jwtVerify is not a function”。
目的是成功提取和验证通过URL查询参数接收的令牌,以确认用户的电子邮件地址。令牌通过电子邮件确认链接生成和发送,并且在接收到带有此令牌的GET请求时,目的是使用FastifyJWT对其进行验证。
此工作流涉及:

  • 正在生成用于电子邮件确认的令牌。
  • 通过电子邮件确认链接中的URL查询参数发送令牌。
const emailToken = await reply.jwtSign({}, {
      sub: email,
      expiresIn: '7d'
    });

    const messageData = {
      from: '[email protected]',
      to: '[email protected]',
      subject: 'Verificação de E-mail',
      text: `Clique neste link para verificar seu e-mail: ${env.APP_URL}/users/verify/email?token=${emailToken}`,
      html: `<p>Clique neste <a href="${env.APP_URL}/users/verify/email?token=${emailToken}">link</a> para verificar seu e-mail.</p>`
    }

    // Envio do e-mail de verificação
    const resMG = await mgClient.messages.create(env.MAILGUN_DOMAIN, messageData);

    console.log('Email enviado com sucesso: ', resMG)

字符串

  • 接收带有令牌的GET请求,并尝试使用FastifyJWT的request.jwtVerify()函数验证它。
import { makeVerifyUserEmailUseCase } from "@/application/factories/user/make-verify-user-email-use-case"
import { FastifyReply, FastifyRequest } from "fastify"
import { z } from "zod"

export default async function verifyUserEmail(request: FastifyRequest, reply: FastifyReply) {
  const verifyUserEmailQuerySchema = z.object({
    token: z.string(),
  })

  const { token } = verifyUserEmailQuerySchema.parse(request.query)
  console.log('TOKEN after parse: ', token)

  try {
    const decodedToken = request.jwtVerify({ token } as any, (error, decodedToken) => {
      if (error) {
        console.log('ERROR!')
        console.error(error)
        return reply.status(401).send('Erro na verificação do token')
      }
      return decodedToken
    })

    console.log('DECODED TOKEN: ', decodedToken)

    const emailToken = (decodedToken as any).sub.email
    console.log(emailToken)
    if ((decodedToken as any) && (decodedToken as any).sub?.email) {
      const verifyUserEmailUseCase = makeVerifyUserEmailUseCase()
      await verifyUserEmailUseCase.execute(emailToken)

      return reply.status(200).send({ message: 'E-mail verificado com sucesso!' })
    }
  } catch (error) {
    console.error(error)
  }

}


但是,代码遇到了request.jwtVerify()函数的问题,该函数似乎不可用或未正确使用,导致了上述错误。
我们的目标是深入了解为什么会发生这种错误以及如何纠正它,从而使用FastifyJWT实现成功的令牌验证。
在试图解决这个问题时,我首先确保@fastify/jwt插件在应用程序中正确安装和配置。插件设置似乎已经到位:

import fastifyJwt from '@fastify/jwt'

app.register(fastifyJwt, {
  secret: env.JWT_SECRET,
  cookie: {
    cookieName: 'refreshToken',
    signed: false,
  },
  sign: {
    expiresIn: '10m',
  },
})


任何疑问都欢迎,如果你需要进一步的信息,我愿意提供它。提前感谢您的任何帮助。

wribegjk

wribegjk1#

试试看:

import { makeVerifyUserEmailUseCase } from "@/application/factories/user/make-verify-user-email-use-case";
import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";

export default async function verifyUserEmail(request: FastifyRequest, reply: FastifyReply) {
  const verifyUserEmailQuerySchema = z.object({
    token: z.string(),
  });

  try {
    const { token } = verifyUserEmailQuerySchema.parse(request.query) as { token: string };
    console.log('TOKEN after parse: ', token);

    const decodedToken = await request.jwtVerify({ token });

    console.log('DECODED TOKEN: ', decodedToken);

    const emailToken = decodedToken.sub.email;
    console.log(emailToken);

    if (decodedToken && decodedToken.sub?.email) {
      const verifyUserEmailUseCase = makeVerifyUserEmailUseCase();
      await verifyUserEmailUseCase.execute(emailToken);

      return reply.status(200).send({ message: 'E-mail verificado com sucesso!' });
    }
  } catch (error) {
    console.error(error);
    return reply.status(401).send('Erro na verificação do token');
  }
}

字符串

相关问题