如何解决在Ionic IOS应用中测试GCP api密钥限制
在我的GCP项目中,我创建了一个新的api密钥。我将密钥限制为IOS应用程序,并正确设置了IOS应用程序捆绑包ID。
api密钥正在Ionic 5应用程序中使用,该应用程序是Xcode内置的,并且在IOS设备上运行。
正在根据Google Maps static API请求传递api密钥。
为了测试api密钥限制,我制作了一个类似于以下内容的网址:
https://maps.googleapis.com/maps/api/staticmap?center=290%20Bremner%20Blvd%2C%20Toronto%2C%20ON%20M5V%203L9&key=[restricted键在这里]&zoom = 12&size = 400x400
当我从笔记本电脑的网络浏览器加载此URL时,会返回一个地图,但我希望它不会起作用,相反,我会收到一个HTTP 403错误。
任何对我在这里缺少的见识的赞赏;在Ionic 5应用程序中使用我的Maps API密钥时,我该如何适当地限制它?
解决方法
我找到了问题的答案:除了使用受限的API密钥外,每个Maps Static 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。