ID client : signature des requêtes

Remarque : Il n'est plus possible de s'inscrire au forfait Premium Google Maps Platform, qui n'est plus disponible non plus pour les nouveaux clients.

Signatures numériques

Comment les signatures numériques fonctionnent-elles ?

Les signatures numériques sont générées à l'aide d'une signature secrète d'URL (ou clé cryptographique) disponible dans la console Google Cloud. Il s'agit essentiellement d'une clé privée, uniquement partagée entre vous et Google, et propre à votre ID client.

Le processus de signature utilise un algorithme de chiffrement qui associe l'URL à votre secret partagé. La signature unique créée permet à nos serveurs de vérifier que tous les sites qui génèrent des requêtes avec votre ID client sont autorisés à le faire.

Signer vos requêtes

Pour signer vos requêtes, procédez comme suit :

Étape 1 : Obtenez votre signature secrète d'URL

Pour obtenir la signature secrète d'URL de votre projet :

  1. Accédez à la page ID client dans la console Cloud.
  2. Le champ Clé contient la signature secrète d'URL actuelle de votre ID client.

Si vous devez en générer une autre, contactez l'assistance.

Étape 2 : Créez une requête non signée

Les caractères non listés dans le tableau ci-dessous doivent être encodés en URL :

Récapitulatif des caractères d'URL valides
EnsembleCaractèresUtilisation de l'URL
Alphanumériques a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 Chaînes de texte, utilisation du schéma (http), port (8080), etc.
Non réservés - _ . ~ Chaînes de texte
Réservés ! * ' ( ) ; : @ & = + $ , / ? % # [ ] Caractères de commande et/ou chaînes de texte

Il en va de même pour les caractères de l'ensemble Réservé s'ils sont transmis dans une chaîne de texte. Pour en savoir plus, consultez la section Caractères spéciaux.

Créez l'URL de requête sans la signature.

Veillez également à inclure l'ID client dans le paramètre client. Exemple :

https://maps.googleapis.com/maps/api/staticmap?center=40.714%2c%20-73.998&zoom=12&size=400x400&client=YOUR_CLIENT_ID

Générer la requête signée

Pour résoudre d'éventuels problèmes, vous pouvez générer automatiquement une signature numérique à l'aide du widget Signer une URL maintenant.

Pour les requêtes générées dynamiquement, vous avez besoin d'une signature côté serveur, ce qui nécessite quelques étapes intermédiaires supplémentaires.

Dans tous les cas, vous devriez obtenir une URL de requête se terminant par le paramètre signature. Exemple :

https://maps.googleapis.com/maps/api/staticmap?center=40.714%2c%20-73.998&zoom=12&size=400x400&client=YOUR_CLIENT_ID
&signature=BASE64_SIGNATURE
  1. Supprimez les parties de l'URL correspondant au schéma de protocole et à l'hôte pour ne laisser que le chemin d'accès et la requête :

  2. /maps/api/staticmap?center=40.714%2c%20-73.998&zoom=12&size=400x400&client=YOUR_CLIENT_ID
    
  3. La signature secrète d'URL affichée est encodée au format Base64 modifié pour les URL.

    La plupart des bibliothèques cryptographiques exigent que la clé se présente sous la forme d'octets bruts. Vous devrez donc probablement décoder votre signature secrète d'URL dans son format brut d'origine avant de signer.

  4. Signez la requête tronquée ci-dessus à l'aide de HMAC-SHA1.
  5. La plupart des bibliothèques cryptographiques génèrent une signature sous la forme d'octets bruts. Vous devrez donc convertir la signature binaire générée au format Base64 modifié pour les URL dans un format pouvant être transmis dans l'URL.

  6. Ajoutez la signature encodée au format Base64 à l'URL de requête non signée d'origine dans le paramètre signature. Exemple :

    https://maps.googleapis.com/maps/api/staticmap?center=40.714%2c%20-73.998&zoom=12&size=400x400&client=YOUR_CLIENT_ID
    &signature=BASE64_SIGNATURE

Pour voir comment implémenter la signature d'URL avec le code côté serveur, consultez Exemple de code pour la signature des URL ci-dessous.

Exemple de code pour la signature des URL

Les sections suivantes expliquent comment implémenter la signature d'URL à l'aide du code côté serveur. Vous devez toujours signer les URL côté serveur afin de ne pas dévoiler votre signature secrète d'URL aux utilisateurs.

Python

L'exemple ci-dessous utilise les bibliothèques Python standards pour signer une URL. (Téléchargez le code.)

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

import hashlib
import hmac
import base64
import urllib.parse as 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, str.encode(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.decode()

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

Java

L'exemple ci-dessous utilise la classe java.util.Base64 disponible depuis JDK 1.8. Les versions plus anciennes auront peut-être besoin d'Apache Commons ou similaire. (Téléchargez le code.)

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;  // JDK 1.8 only - older versions may need to use Apache Commons or similar.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class UrlSigner {

  // Note: Generally, you should store your private key someplace safe
  // and read them into your code

  private static String keyString = "YOUR_PRIVATE_KEY";

  // The URL shown in these examples is a static URL which should already
  // be URL-encoded. In practice, you will likely have code
  // which assembles your URL from user or web service input
  // and plugs those values into its parameters.
  private static String urlString = "YOUR_URL_TO_SIGN";

  // This variable stores the binary key, which is computed from the string (Base64) key
  private static byte[] key;

  public static void main(String[] args) throws IOException,
    InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    String inputUrl, inputKey = null;

    // For testing purposes, allow user input for the URL.
    // If no input is entered, use the static URL defined above.
    System.out.println("Enter the URL (must be URL-encoded) to sign: ");
    inputUrl = input.readLine();
    if (inputUrl.equals("")) {
      inputUrl = urlString;
    }

    // Convert the string to a URL so we can parse it
    URL url = new URL(inputUrl);

    // For testing purposes, allow user input for the private key.
    // If no input is entered, use the static key defined above.
    System.out.println("Enter the Private key to sign the URL: ");
    inputKey = input.readLine();
    if (inputKey.equals("")) {
      inputKey = keyString;
    }

    UrlSigner signer = new UrlSigner(inputKey);
    String request = signer.signRequest(url.getPath(),url.getQuery());

    System.out.println("Signed URL :" + url.getProtocol() + "://" + url.getHost() + request);
  }

  public UrlSigner(String keyString) throws IOException {
    // Convert the key from 'web safe' base 64 to binary
    keyString = keyString.replace('-', '+');
    keyString = keyString.replace('_', '/');
    System.out.println("Key: " + keyString);
    // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.
    this.key = Base64.getDecoder().decode(keyString);
  }

  public String signRequest(String path, String query) throws NoSuchAlgorithmException,
    InvalidKeyException, UnsupportedEncodingException, URISyntaxException {

    // Retrieve the proper URL components to sign
    String resource = path + '?' + query;

    // Get an HMAC-SHA1 signing key from the raw key bytes
    SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");

    // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(sha1Key);

    // compute the binary signature for the request
    byte[] sigBytes = mac.doFinal(resource.getBytes());

    // base 64 encode the binary signature
    // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.
    String signature = Base64.getEncoder().encodeToString(sigBytes);

    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-');
    signature = signature.replace('/', '_');

    return resource + "&signature=" + signature;
  }
}

Node.js

L'exemple ci-dessous utilise des modules Node natifs pour signer une URL. (Téléchargez le code.)

'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;
}

C#

L'exemple ci-dessous utilise la bibliothèque System.Security.Cryptography par défaut pour signer une requête d'URL. Notez que nous devons convertir l'encodage Base64 par défaut pour implémenter une version sécurisée pour les URL. (Téléchargez le code.)

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace SignUrl {

  public struct GoogleSignedUrl {

    public static string Sign(string url, string keyString) {
      ASCIIEncoding encoding = new ASCIIEncoding();

      // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
      string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
      byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);

      Uri uri = new Uri(url);
      byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);

      // compute the hash
      HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
      byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);

      // convert the bytes to string and make url-safe by replacing '+' and '/' characters
      string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");

      // Add the signature to the existing URI.
      return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature;
    }
  }

  class Program {

    static void Main() {

      // Note: Generally, you should store your private key someplace safe
      // and read them into your code

      const string keyString = "YOUR_PRIVATE_KEY";

      // The URL shown in these examples is a static URL which should already
      // be URL-encoded. In practice, you will likely have code
      // which assembles your URL from user or web service input
      // and plugs those values into its parameters.
      const  string urlString = "YOUR_URL_TO_SIGN";

      string inputUrl = null;
      string inputKey = null;

      Console.WriteLine("Enter the URL (must be URL-encoded) to sign: ");
      inputUrl = Console.ReadLine();
      if (inputUrl.Length == 0) {
        inputUrl = urlString;
      }

      Console.WriteLine("Enter the Private key to sign the URL: ");
      inputKey = Console.ReadLine();
      if (inputKey.Length == 0) {
        inputKey = keyString;
      }

      Console.WriteLine(GoogleSignedUrl.Sign(inputUrl,inputKey));
    }
  }
}

Exemples dans d'autres langages

Des exemples dans d'autres langages sont disponibles dans le projet url-signing.

Dépannage

Si le format de votre requête est incorrect ou si la requête fournit une signature non valide, l'API affiche une erreur HTTP 403 (Forbidden).

Pour résoudre le problème, copiez l'URL de la requête, supprimez le paramètre de requête signature, puis générez de nouveau une signature valide en suivant les instructions ci-dessous :

Pour générer une signature numérique avec votre ID client à l'aide du widget Signer une URL maintenant ci-dessous :

  1. Récupérez la signature secrète d'URL de votre ID client, comme indiqué dans Étape 1 : Obtenez votre signature secrète d'URL.
  2. Dans le champ URL, collez votre URL de requête non signée issue de Étape 2 : Créez une requête non signée.
  3. Dans le champ Signature secrète d'URL, collez votre signature secrète d'URL provenant de l'étape 2.
    Une signature numérique est générée en se basant sur votre URL de requête non signée et votre signature secrète. Elle est ajoutée à votre URL d'origine.
  4. Le champ Votre URL signée qui s'affiche contient votre URL signée numériquement.