【问题标题】:Can't match signature as generated by Google API documentation page与 Google API 文档页面生成的签名不匹配
【发布时间】:2017-10-17 00:54:04
【问题描述】:

当我将我的 url 和签名放入提供的空间以生成示例签名 url 时,我的签名与 Google 的不同。我已经检查并重新检查,所以我认为没有任何愚蠢的错误。那么也许我误解了某些东西,或者我从 Python 代码中翻译了一些错误的东西?

我的代码:

  def my_map_url
    domain = "http://maps.googleapis.com/"
    key = Figaro.env.maps_browser_api_key
    path = "maps/api/staticmap?key=#{key}&size=450x300"
    object.each do |location|
      path += "&markers=#{location.latitude}%2C#{location.longitude}"
    end
    puts domain + path # What I put into Google's url input box
    domain + path + "&signature=#{hmac_sha1(path)}"
  end

  def hmac_sha1(data)
    digest = OpenSSL::Digest.new('sha1')
    secret = Base64.urlsafe_decode64(ENV["MAPS_STATIC_SECRET"])
    hmac = OpenSSL::HMAC.digest(digest, secret, data)
    return Base64.urlsafe_encode64(hmac)
  end

谷歌页面https://developers.google.com/maps/documentation/static-maps/get-api-key?hl=en_US#sample-code-for-url-signing

以及他们提供的 Python 示例:

#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Signs a URL using a URL signing secret """

import hashlib
import hmac
import base64
import urlparse

def sign_url(input_url=None, secret=None):
  """ Sign a request URL with a URL signing secret.

      Usage:
      from urlsigner import sign_url

      signed_url = sign_url(input_url=my_url, secret=SECRET)

      Args:
      input_url - The URL to sign
      secret    - Your URL signing secret

      Returns:
      The signed request URL
  """

  if not input_url or not secret:
    raise Exception("Both input_url and secret are required")

  url = urlparse.urlparse(input_url)

  # We only need to sign the path+query part of the string
  url_to_sign = url.path + "?" + url.query

  # Decode the private key into its binary format
  # We need to decode the URL-encoded private key
  decoded_key = base64.urlsafe_b64decode(secret)

  # Create a signature using the private key and the URL-encoded
  # string using HMAC SHA1. This signature will be binary.
  signature = hmac.new(decoded_key, url_to_sign, hashlib.sha1)

  # Encode the binary signature into base64 for use within a URL
  encoded_signature = base64.urlsafe_b64encode(signature.digest())

  original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query

  # Return signed URL
  return original_url + "&signature=" + encoded_signature

if __name__ == "__main__":
  input_url = raw_input("URL to Sign: ")
  secret = raw_input("URL signing secret: ")
  print "Signed URL: " + sign_url(input_url, secret)

【问题讨论】:

    标签: python ruby google-maps hmacsha1


    【解决方案1】:

    python 版本中的urlparse.urlparse(input_url).path/ 开头。在 ruby​​ 版本中,您使用相对路径 path = "maps/api/staticmap?key=#{key}&size=450x300"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 2012-04-19
      • 2018-08-14
      • 2021-01-02
      • 1970-01-01
      • 2020-03-03
      • 2023-04-04
      相关资源
      最近更新 更多