本文介绍了Google Cloud Key Management Service签署JSON Web令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我在以下位置尝试了该解决方案:但这不起作用.

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

创建签名:

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

我无法弄清楚代码出了什么问题.

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

推荐答案

signatureObj.signature是一个缓冲区,而不是字符串.可悲的是,文档在这一点上是不正确的.

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

跳过base64编码/解码步骤应该会产生正确的结果( verify.verify 可以接受Buffer作为签名参数.

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

要将签名的内容实际编码到您的JWT中,您需要使用signatureObj.signature.toString('base64')之类的东西.

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

这篇关于Google Cloud Key Management Service签署JSON Web令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 13:06