在我的GCP项目中,我创建了一个新的API键。我将密钥限制为IOS应用程序,并正确设置了我的IOS应用程序包id。
应用程序接口密钥正在Ionic 5应用程序中使用,该应用程序是用Xcode构建的,并在IOS设备上运行。
正在通过Google Maps static API请求传递api密钥。
为了测试api密钥限制,我制作了一个url,如下所示:
[https://maps.googleapis.com/maps/api/staticmap?center=290%20Bremner%20Blvd%2C%20Toronto%2C%20ON%20M5V%203L9&key=[restricted](https://maps.googleapis.com/maps/api/staticmap?center=290%20Bremner%20Blvd%2C%20Toronto%2C%20ON%20M5V%203L9&key=%5Brestricted)键在此处]&zoom=12&size=400x400
当我从我的笔记本电脑web浏览器加载这个url时,返回了一个地图,但我预计这不会起作用,相反,我会收到一个http 403错误。
感谢您对我在这里遗漏的内容有什么见解;当我在Ionic 5应用程序中使用地图api密钥时,如何正确地限制它?
发布于 2020-11-28 01:01:30
我找到了问题的答案:除了使用受限制的API密钥之外,每个Maps静态API请求在发出请求时都必须经过数字签名。
下面是Google的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;
}
更多信息/文档请点击此处:
https://developers.google.com/maps/documentation/maps-static/get-api-key#gen-sig
https://stackoverflow.com/questions/63404113
复制相似问题