Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Allow local options to override signing key #328

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

salmanm
Copy link
Member

@salmanm salmanm commented Feb 14, 2024

Just added a test case to demonstrate a problem I've noticed. I'm a bit surprised to see this not working which made me think whether I'm expecting correct behaviour! 😅

Basically I can not override signing key/secret in the reply.jwtSign

Please could someone validate if the test case I've added is the expected one? I'll update the code then.

Thanks

Checklist

@jmjf
Copy link
Contributor

jmjf commented Jun 29, 2024

TL:DR; Use a namespace.

  const fastify = Fastify()
  fastify.register(jwt, options)
  fastify.register(jwt, { ...options, secret: 'something-else', namespace: 'refresh' });

  fastify.post('/sign', async function (request, reply) {
    const { token, refreshToken } = request.body
    const refreshTokenSigned = await reply.refreshJwtSign(refreshToken) // signing by different key
    const tokenSigned = await reply.jwtSign(token)
    return reply.send({ tokenSigned, refreshTokenSigned })
  })

Before I came to that answer, I did some digging in the debugger. Details below in case you're interested.

At

const signerOptions = mergeOptionsWithKey(options.sign || options, secretOrPrivateKey)

options (from replySign scope) = { key: 'something-else' }
secretOrPrivateKey (from fastifyJwt scope) = 'test'

When this line executes, signerOptions is set to { key: 'test' }.

mergeOptionsWithKey at L269-L276
gets parameter values options = { key: 'something-else' }, useProvidedPrivateKey = 'test'. So it takes take the first branch and test becomes the key.

I experimented a bit trying to find a way to make it work, but broke other tests every time.

requestVerify at

const verifierOptions = mergeOptionsWithKey(options.verify || options, secretOrPublicKey)
is doing the same thing, so it seems that the intended behavior is that you can't override the key in reply.jwtSign or request.jwtVerify by passing options.

But, as noted above, you can use a namespace and use the namespaced decorators. (Today was a good day because I learned something.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants