auth0 / node-oauth2-jwt-bearer

Monorepo for libraries that protect Node APIs with OAuth2 Bearer JWTs
MIT License
95 stars 31 forks source link

publicKey without discovery #133

Open cerpins opened 9 months ago

cerpins commented 9 months ago

Checklist

Describe the problem you'd like to have solved

It seems possible to avoid discovery altogether by specifying issuer instead of issuerBaseURL, and this is perfectly fine with symmetrical algorithms. However, it seems impossible to provide an asymmetrical algorithm and not specify issuerBaseURL.

Describe the ideal solution

I would like to pass the public key explicitly without doing discovery. So something like defining issuer, audience, and then public key in secret. The library jose seems to allow passing the public key already, but we never get here because node-oauth2-jwt-bearer will throw before that during validation.

Alternatives and current workarounds

Currently not possible.

Additional context

No response

gaving commented 6 months ago

I've came across this issue trying to migrate from express-jwt and having the same problem.

Is there any suggested workaround? Hoping to not have to introduce JWKS for this asymmetrical setup where I have the public key available to me which I hoped to pass into secret.

Otherwise faced with jose or a jsonwebtoken approach but not sure where to turn.

ehaynes99 commented 3 months ago

There's no way to do it currently. You can pass a custom issuer and jwksUri param, but you would still have to host the JWKS yourself. The secret parameter can only be used with symmetric algorithms. As it's published by Auth0, I expect they're largely focused on their workflow where you would have the jwks hosted by them.

It's pretty straightforward with jsonwebtoken, though:

import fs from 'node:fs/promises'
import jsonWebToken from 'jsonwebtoken'

const TEN_HOURS = 10 * 60 * 60
const AUDIENCE = 'https://example.com/api'

const payload = {
  iss: 'https://example.com',
  sub: '0123456789abcdef',
  aud: [AUDIENCE],
  iat: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + TEN_HOURS,
  scope: 'openid profile email offline_access',
  azp: '0123456789abcdef',
}

const privateKey = await fs.readFile('/path/to/private.pem', 'utf8')
const publicKey = await fs.readFile('/path/to/public.pem', 'utf8')

const token = jsonWebToken.sign(payload, privateKey, { algorithm: 'RS256' })

try {
  const payload = jsonWebToken.verify(token, publicKey, {
    algorithms: ['RS256'],
    audience: AUDIENCE,
  }) as jsonWebToken.JwtPayload

  // or if you need `{ header, payload, signature }` for some reason:
  // const { header, payload, signature } = jsonWebToken.verify(token, publicKey, {
  //   algorithms: ['RS256'],
  //   audience: AUDIENCE,
  //   complete: true,
  // }) as jsonWebToken.Jwt
  console.log('payload:', payload)
} catch (error) {
  // throws if expired, invalid signature, incorrect audience, etc.
  console.error(error)
}