1

I am trying to generate an accessToken with algorithm ES256 and I use the following very very simple code:

const jwt = require('jsonwebtoken')

const accessToken = jwt.sign(
  { name: 'John' },
  'testsecret',
  { expiresIn: '24h' },
  { algorithm: 'ES256' }
)

console.log(accessToken)

And I got a token as below:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiIsImlhdCI6MTYxNDY4MzUxNCwiZXhwIjoxNjE0NzY5OTE0fQ.Q9quAufyTQvPvKrTUXzRDUo-o0M4yXSXjqU4vZ9nvvA

I tried pasting this to jwt.io and it seems that it is a HS256 token instead of ES256, did I miss anything?

There is something that I did not do correctly. You can always paste the above code to nodejs and you will see.

Daryl Wong
  • 2,023
  • 5
  • 28
  • 61

1 Answers1

4

You just need to combine the expiresIn and algorithm arguments - the module takes a single options object:

const jwt = require('jsonwebtoken');
const privatekey = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEICXoLhGdD6jzX5ePTY9O9YBgv0ZZ6oBWDRsjKaeASXp6oAoGCCqGSM49
AwEHoUQDQgAELCnuRSU9Vf+bx65i3Vbibj123RQFrIEaXuMuXunzPXGURKge07fy
FoiMucdGZ2MZGsm37JdlnVGd5yU1h4D4Rg==
-----END EC PRIVATE KEY-----`

const payload = {"id":1}

const accessToken = jwt.sign(payload, privatekey, {
  expiresIn: "24h",
  algorithm: "ES256",
});
jps
  • 20,041
  • 15
  • 75
  • 79
Jack Dunleavy
  • 249
  • 1
  • 7
  • @jps you got ES256? – Daryl Wong Mar 02 '21 at 12:11
  • yes! I used exactly that code from the answer. Of course you need a ES256 key for it. So again, what error do you get? I see in the last edit of your question you replaced the private key with a simple string. That can't work. Before you loaded a key from a file. – jps Mar 02 '21 at 12:14
  • there is no error message, may I know how you have generated the private key? I use something like "testsecret" like the code above – Daryl Wong Mar 02 '21 at 12:16
  • see my comment above, you need a proper key and seems you loaded one before. You can generate keys on https://8gwifi.org/jwsgen.jsp – jps Mar 02 '21 at 12:19
  • openssl ecparam -genkey -name secp256k1 -noout -out private.pem. this is now I have generated the key – Daryl Wong Mar 02 '21 at 12:20
  • 1
    I edited the answer to show a complete example. Please try that, it should work for you. – jps Mar 02 '21 at 12:23
  • regarding your openssl command, see [this comment](https://stackoverflow.com/questions/66349140/invalid-jwt-signature-with-es256/66371706#comment117300743_66349140). You need secp256r1. – jps Mar 02 '21 at 12:47