如何在JavaScript中生成有效签名,我有一个业务密钥和客户端ID但无法继续进行静态映射api有效url签名,因为我使用JavaScript调用此API并且想要发送签名和客户端ID以充分利用我的使用限制。
答案 0 :(得分:3)
这是Google提供的示例Javascript(node.js)代码的链接,用于在其documentation中签名静态地图URL:
https://github.com/googlemaps/url-signing/blob/gh-pages/urlSigner.js
我已经将代码转换为gmaps-url-signer节点/ npm模块。您可以通过以下方式使用它通过gmaps-url-signer库对静态地图URL进行签名:
const urlSigner = require('gmaps-url-signer');
const key = 'my_google_api_key';
const secret = 'my_static_maps_secret';
const domain = 'http://maps.googleapis.com';
// Path to your static map
let path = '/maps/api/staticmap?zoom=2&scale=1&size=350x250&maptype=terrain&format=png&visual_refresh=true';
path += `&key=${key}`;
console.log('Full signed URL:');
console.log(domain + urlSigner.sign(path, secret));
答案 1 :(得分:2)
包括以下语言的示例,包括Node / JS:
对于Node / JS,它看起来像这样:
'use strict'
const crypto = require('crypto');
const url = require('url');
/**
* Convert from 'web safe' base64 to true base64.
*
* @param {string} safeEncodedString The code you want to translate
* from a web safe form.
* @return {string}
*/
function removeWebSafe(safeEncodedString) {
return safeEncodedString.replace(/-/g, '+').replace(/_/g, '/');
}
/**
* Convert from true base64 to 'web safe' base64
*
* @param {string} encodedString The code you want to translate to a
* web safe form.
* @return {string}
*/
function makeWebSafe(encodedString) {
return encodedString.replace(/\+/g, '-').replace(/\//g, '_');
}
/**
* Takes a base64 code and decodes it.
*
* @param {string} code The encoded data.
* @return {string}
*/
function decodeBase64Hash(code) {
// "new Buffer(...)" is deprecated. Use Buffer.from if it exists.
return Buffer.from ? Buffer.from(code, 'base64') : new Buffer(code, 'base64');
}
/**
* Takes a key and signs the data with it.
*
* @param {string} key Your unique secret key.
* @param {string} data The url to sign.
* @return {string}
*/
function encodeBase64Hash(key, data) {
return crypto.createHmac('sha1', key).update(data).digest('base64');
}
/**
* Sign a URL using a secret key.
*
* @param {string} path The url you want to sign.
* @param {string} secret Your unique secret key.
* @return {string}
*/
function sign(path, secret) {
const uri = url.parse(path);
const safeSecret = decodeBase64Hash(removeWebSafe(secret));
const hashedSignature = makeWebSafe(encodeBase64Hash(safeSecret, uri.path));
return url.format(uri) + '&signature=' + hashedSignature;
}
答案 2 :(得分:1)
Google不建议使用JavaScript对URL进行签名,因为它会向用户公开加密密钥。
您可以在此链接中看到:
https://developers.google.com/maps/documentation/business/faq#signature_jses
答案 3 :(得分:1)
如果你的意思是你有一个Javascript服务器(NodeJS / Meteor)并且想要获得签名的URL,我会使用这个包。