Google Cloud Key Management Service to sign JSON Web Tokens

不打扰是莪最后的温柔 提交于 2020-01-04 05:32:04

问题


First of all I tried the solution at: Using Google Cloud Key Management Service to sign JSON Web Tokens But it doesn't work.

Creating signature:

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}`

Then verifying:

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')

I'm not able to figure what is wrong with the code.


回答1:


signatureObj.signature is a Buffer, not a String. Sadly, the documentation is incorrect on this point.

Skipping the base64 encode/decode steps should yield the proper results (verify.verify can accept a Buffer as the signature argument).

For actually encoding the contents of the signature into your JWT, you'll want something like signatureObj.signature.toString('base64').



来源:https://stackoverflow.com/questions/55828435/google-cloud-key-management-service-to-sign-json-web-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!