Open trasherdk opened 2 years ago
A similar version that encode, sign, verify and decode JWT token. It does NOT validate on jwt.io
#!/bin/bash
BASE=$(dirname $(realpath $0))
echo "Working in ${BASE}"
cd ${BASE}
CA="${BASE}/ca"
TEMP="${BASE}/temp"
openssl ecparam -genkey -name prime256v1 -noout -out "${CA}/private-jwt-key.pem" || exit 1
openssl ec -in "${CA}/private-jwt-key.pem" -pubout -out "${CA}/public-jwt-key.pem" || exit 1
import { readFileSync } from 'fs'
import jsrsasign from 'jsrsasign'
import path, { resolve } from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const Private = readFileSync(resolve(__dirname, '../ca/private-jwt-key.pem')).toString('utf8')
const Public = readFileSync(resolve(__dirname, '../ca/public-jwt-key.pem')).toString('utf8')
const tNow = jsrsasign.KJUR.jws.IntDate.get('now')
const tEnd = jsrsasign.KJUR.jws.IntDate.get('now + 1day')
const teamId = 'SEARCHADS.xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
const clientId = 'foo'
const keyId = 'xxxxxx-xxxx-xxxx-xxxxxxxxxxx'
const oHeader = {
alg: 'ES256',
kid: keyId
}
const oPayload = {
iss: teamId,
iat: tNow,
exp: tEnd,
aud: 'https://appleid.apple.com',
sub: clientId
}
const sHeader = JSON.stringify(oHeader)
const sPayload = JSON.stringify(oPayload)
let sResult
try {
const sKey = jsrsasign.KEYUTIL.getKey(Private)
sResult = jsrsasign.KJUR.jws.JWS.sign('ES256', sHeader, sPayload, sKey)
} catch (error) {
console.log(error)
process.exit()
}
console.log(sResult)
console.log('verifyJWT:', jsrsasign.KJUR.jws.JWS.verifyJWT(sResult, Public, {
alg: ['ES256'],
verifyAt: jsrsasign.KJUR.jws.IntDate.get('now')
}))
let headerObj
let payloadObj
try {
headerObj = jsrsasign.KJUR.jws.JWS.readSafeJSONString(jsrsasign.b64utoutf8(sResult.split('.')[0]))
} catch (error) {
console.log('headerObj:', error)
process.exit()
}
try {
payloadObj = jsrsasign.KJUR.jws.JWS.readSafeJSONString(jsrsasign.b64utoutf8(sResult.split('.')[1]))
} catch (error) {
console.log('payloadObj:', error)
process.exit()
}
console.log('Header:', headerObj)
console.log('Payload:', payloadObj)
Generate a private key:
openssl ecparam -genkey -name prime256v1 -noout -out private-key.pem
Generate a public key from the private key:
openssl ec -in private-key.pem -pubout -out public-key.pem
Source: https://github.com/kjur/jsrsasign/issues/541#issuecomment-1063946948