fastify / fastify-jwt

JWT utils for Fastify
MIT License
512 stars 99 forks source link

Asynchronous secret Indicates the input parameter without type prompt #308

Closed Fuarm closed 1 year ago

Fuarm commented 1 year ago

Prerequisites

Fastify version

4.23.2

Plugin version

7.2.1

Node.js version

16.19.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13.5

Description

document example

fastify.register(jwt, {
  secret: function (request, token) {
    return Promise.resolve('supersecret')
  }
})

Getting secret asynchronously in fast-jwt has no request param

function getAsyncKey(handler, decoded, callback) {
  const result = handler(decoded, callback)

  if (result && typeof result.then === 'function') {
    result
      .then(key => {
        // This avoids the callback to be thrown twice if callback throws
        process.nextTick(() => callback(null, key))
      })
      .catch(callback)
  }
}

Steps to Reproduce

fastify.register(jwt, {
  secret: function (request, token) {
    console.log("request: ", request);
    return Promise.resolve('supersecret')
  }
})
// print
request {
  header: { alg: undefined, typ: 'JWT', kid: undefined },
  payload: {  }
}

Expected Behavior

No response

climba03003 commented 1 year ago

Can you provide a full reproducible code snippet? The secret function is not called by fast-jwt directly but inside this library.

Fuarm commented 1 year ago
import Fastify, { FastifyInstance, FastifyRequest } from "fastify";
import fastifyJwt, { TokenOrHeader } from "@fastify/jwt";

const server: FastifyInstance = Fastify({
  logger: true
});

server.register(fastifyJwt, {
  secret: async (request: FastifyRequest | TokenOrHeader) => {
    console.log(request);
    return "secret";
  }
});

server.get("/test", (request, reply) => {
  const token = server.jwt.sign({ userId: 12 }, { expiresIn: "2h" });
  reply.send(token);
});

/**
 * 服务启动
 * @param port 端口
 */
const startServer = async (port: number) => {
  try {
    await server.listen({ port });
  } catch (err) {
    server.log.error(err);
    process.exit(1);
  }
};
startServer(3000)
climba03003 commented 1 year ago

Function based secret is supported by the request.jwtVerify() and reply.jwtSign() methods and is called with request, token, and callback parameters.

I would say that it is a correct behavior since the document already told you function based secret only supported by the above two methods.