const { JWS, JWK } = require('node-jose')
const axios = require('axios')
async function decodeIdToken(token, baseUrl) {
// fetch server public key
const response = await axios.get(baseUrl + '/v1/oauth/certs')
// create JWK
const publicKey = await JWK.asKey(response.data.keys[0])
// decode and verify id token
const { payload } = await JWS.createVerify(publicKey).verify(token)
// parse payload and retrieve sub
const { sub } = JSON.parse(payload.toString())
return sub
}
Decode UserInfo JWE
const { JWE, JWK } = require('node-jose')
async function decryptJWE(encryptedPayload, privateKey) {
try {
// import privateKey as a jwk
const key = await JWK.asKey(privateKey, 'pem')
// decrypt jwe
const result = await JWE.createDecrypt(key).decrypt(encryptedPayload)
// parse plaintext buffer to string then to JSON
return JSON.parse(result.plaintext.toString())
} catch (e) {
console.error(e)
}
}
Verify Signature
function verifySignatures(decrypted, userPublicKey) {
for (const fieldKey in decrypted) {
const { value, signature } = decrypted[fieldKey]
// Verify sha256 signature of each field
const verify = crypto.createVerify('SHA256').update(JSON.stringify({ [fieldKey]: value })).end()
// Assign verified flag for each field
decrypted[fieldKey].verified = verify.verify(userPublicKey, signature, 'hex')
}
}