首先,我尝试了以下解决方案:Using Google Cloud Key Management Service to sign JSON Web Tokens 但它不起作用。
创建签名:
const TimeStamp = Math.floor(new Date().getTime() / 1000)
let body = base64url(
JSON.stringify({
alg: 'RS256',
typ: 'JWT'
})
)
body += '.'
body += base64url(
JSON.stringify({
iss: 'some-iss',
aud: 'some-aud',
iat: TimeStamp,
exp: TimeStamp + parseInt(process.env.TOKEN_EXPIRY, 10)
})
)
const hashedMessage = crypto
.createHash('sha256')
.update(body)
.digest('base64')
const digest = { sha256: hashedMessage }
const [signatureObj] = await client
.asymmetricSign({ name, digest })
.catch(console.error)
const signature = base64url(signatureObj.signature)
const token = `${body}.${signature}`
然后验证:
const[publicKeyObject] = await client.getPublicKey({ name }).catch(console.error)
const publicKey = publicKeyObject.pem
const verify = crypto.createVerify('sha256')
verify.write(body)
verify.end()
verify.verify(publicKey, base64url.decode(signature), 'base64')
我无法弄清楚代码有什么问题。