首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GCP api密钥限制

GCP api密钥限制
EN

Stack Overflow用户
提问于 2020-08-14 06:35:31
回答 1查看 208关注 0票数 0

在我的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密钥时,如何正确地限制它?

EN

回答 1

Stack Overflow用户

发布于 2020-11-28 01:01:30

我找到了问题的答案:除了使用受限制的API密钥之外,每个Maps静态API请求在发出请求时都必须经过数字签名。

下面是Google的Node js示例代码,告诉你如何做到这一点:

代码语言:javascript
复制
'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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63404113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档