在 Node.js 中请求签名
本文介绍了在 Node.js 中实现 请求签名 的示例。
# 依赖项
此示例仅使用 Node.js 的核心依赖项:crypto
和 url
。
# 示例
以下简单示例实现了 请求签名 指南中描述的算法。最重要的是使用 crypto
模块,并使用适当的 SHA256
算法,并按以下顺序提供参数:method
、url
、timestamp
、body
。
method
参数应以大写形式提供,url
应仅包含 URL 中的路径,而不是完整的 URL 地址。完整的 URL 地址应转换为 /webhook?a=1
。
如果算法运行正常,它应该生成与下面给出的签名相同的签名:56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762
,对应以下参数
-
apiSecret=SECRET
-
method=POST
-
uri=http://demo.example.com/webhook?a=1
-
timestamp=1563276169752
-
body={a:1}
const crypto = require( 'crypto' );
function generateSignature( apiSecret, method, uri, timestamp, body ) {
const url = new URL( uri );
const path = url.pathname + url.search;
const hmac = crypto.createHmac( 'SHA256', apiSecret );
hmac.update( `${ method.toUpperCase() }${ path }${ timestamp }` );
if ( body ) {
hmac.update( Buffer.from( JSON.stringify( body ) ) );
}
return hmac.digest( 'hex' );
}
const expectedSignature = '56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762';
const generatedSignature = generateSignature(
'SECRET',
'POST',
'http://demo.example.com/webhook?a=1',
1563276169752,
{ a: 1 }
);
console.log( expectedSignature === generatedSignature );
# 使用
运行
node index.js