Friday, December 4, 2020

init failed:Error: not supported argument while generating JWT token with jsrsasign - Node JS

I was getting "init failed:Error: not supported argument" error while trying to generate the JWT Token with RS256 algorithm through "jsrsasign" npm module.


const jsrsasign = require('jsrsasign')

const fs = require('fs');

const EXPIRATION = 60 * 60 // 1 hour

  const header = {

    'alg': 'RS256',

    'typ': 'JWT'

  }

  const payload = {

    'exp': Math.round(new Date().getTime() / 1000) + EXPIRATION,

    'iss': 'test',

    'sub': 'test',

    'aud': 'test',

    'custom-prop': 'test'

  }  

  const privateKey = fs.readFileSync('privateKeyfile.key); 

  const jwtToken = jsrsasign.jws.JWS.sign('RS256', JSON.stringify(header), JSON.stringify(payload), JSON.stringify(privateKey))


But the JWT token generation was successful with the HS256 algorithm


const jsrsasign = require('jsrsasign')

const fs = require('fs');

const EXPIRATION = 60 * 60 // 1 hour

  const header = {

    'alg': 'HS256',

    'typ': 'JWT'

  }

  const payload = {

    'exp': Math.round(new Date().getTime() / 1000) + EXPIRATION,

    'iss': 'test',

    'sub': 'test',

    'aud': 'test',

    'custom-prop': 'test'

  }  

  const privateKey = fs.readFileSync('privateKeyfile.key); 

  const jwtToken = jsrsasign.jws.JWS.sign('HS256', JSON.stringify(header), JSON.stringify(payload), JSON.stringify(privateKey))


To support the RS256 algorithm, changed the "jsrsasign" to  "jsonwebtoken" module.


const jwt = require('jsonwebtoken');

const fs = require('fs');

const EXPIRATION = 60 * 60 // 1 hour

const header = {

    'alg': 'HS256',

    'typ': 'JWT'

 }

  const payload = {

    'exp': Math.round(new Date().getTime() / 1000) + EXPIRATION,

    'iss': 'test',

    'sub': 'test',

    'aud': 'test',

    'custom_attr': 'test'

  }  

const privateKey = fs.readFileSync(process.env.PRIVATE_KEY); 

const jwtToken=jwt.sign(JSON.stringify(payload), privateKey,{ 'algorithm': 'RS256' });


The JWT token generation with the RS256 algorithm was successful after switching to "jsonwebtoken" module