Digital Signature Guide Stay organized with collections Save and categorize content based on your preferences.
AI-generated Key Takeaways
Digitally signing Google Maps API requests enhances security by using a unique URL signing secret to verify requests, supplementing API key usage.
You can restrict your API key to only accept signed requests by adjusting the "Unsigned requests" quota in the Google Cloud console for the Maps Static API or Street View Static API.
Generating a signed request involves obtaining your URL signing secret, constructing the unsigned request URL, and then using the secret to create and append the signature.
Server-side code examples in Python and Java are provided to guide the implementation of digital signatures for dynamic requests.
URL signing secrets should be kept confidential, and requests should use either a client ID or an API key, not both, with UTF-8 encoding enforced.
Digitally sign your request with an API key
Depending on your usage, a digital signature - in addition to an API key - may be required to authenticate requests. See the following articles:
How digital signatures work
Digital signatures are generated using aURL signing secret, which is available on the Google Cloud console. This secret is essentially a private key, only shared between you and Google, and is unique to your project.
The signing process uses an encryption algorithm to combine the URL and your shared secret. The resulting unique signature allows our servers to verify that any site generating requests using your API key is authorized to do so.
We strongly recommend that you use both an API key and digital signature,regardless of your usage.Limit unsigned requests
To ensure that your API key only accepts signed requests:
- Go to theGoogle Maps Platform Quotas page in the Cloud console.
- Click the project drop-down and select the same project you used when you created the API key for your application or site.
- Select theMaps Static API orStreet View Static API from the APIs drop-down.
- Expand theUnsigned requests section.
- In theQuota Name table, click the edit button next to the quota you want to edit. For example,Unsigned requests per day.
- UpdateQuota limit in theEdit Quota Limit pane.
- SelectSave.
Signing your requests
Signing your requests comprises the following steps:
- Step 1:Get your URL signing secret
- Step 2:Construct an unsigned request
- Step 3:Generate the signed request
Step 1: Get your URL signing secret
Warning: Please keep your URL signing secret secure. Donot pass it in any requests, store it on any websites, or post it to any public forum. Anyone obtaining your URL signing secret could spoof requests using your identity.To get your project URL signing secret:
- Go to theGoogle Maps Platform Credentials page in the Cloud console.
- Select the project drop-down and select the same project you used when you created the API key for the Maps Static API or Street View Static API.
- Scroll down to theSecret Generator card. TheCurrent secret field contains your current URL signing secret.
- The page also features theSign a URL now widget that allows you to automatically sign the Maps Static API or Street View Static API request using your current signing secret. Scroll down to theSign a URL now card to access it.
To get a new URL signing secret, selectRegenerate Secret. The previous secret will expire 24 hours after you've generated a new secret. After the 24 hours have passed, requests containing the old secret no longer work.
Step 2: Construct your unsigned request
Warning: Requests containing both a client ID and an API keymay result in unexpected API behavior or unintended billing behavior. To prevent this,make sure your requests use only one of these parameters.Important: All Google services require UTF-8 character encoding (which implicitly includes ASCII). If your applications operate using non-ASCII character sets, make sure they construct URLs using UTF-8 and properlyURL-encode them!Charactersnot listed in the table below must be URL-encoded:
| Set | characters | URL usage |
|---|---|---|
| Alphanumeric | 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 | Text strings, scheme usage (http), port (8080), etc. |
| Unreserved | - _ . ~ | Text strings |
| Reserved | ! * ' ( ) ; : @ & = + $ , / ? % # [ ] | Control characters and/or Text Strings |
The same applies to any characters in theReserved set, if they are passed inside a text string. For more info, seeSpecial characters.
Construct your unsigned request URL without the signature. For instructions, see the following developer documentation:
Make sure to also include the API key in thekey parameter. For example:
https://maps.googleapis.com/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEYGenerate the signed request
For one-off use cases, such as hosting a simple Maps Static API or Street View Static API image on your web page, or troubleshooting purposes, you can generate a digital signature automatically using the availableSign a URL now widget.
For dynamically generated requests, you needserver-side signing, which requires a few additional intermediate steps
Either way, you should end up with a request URL that has asignature parameter appended to the end. For example:
https://maps.googleapis.com/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEY&signature=BASE64_SIGNATUREUsing the Sign a URL now widget
To generate a digital signature with an API key using theSign a URL now widget in the Google Cloud console:
- Locate theSign a URL now widget, as described inStep 1: Get your URL signing secret.
- In theURL field, paste your unsigned request URL fromStep 2: Construct your unsigned request.
- TheYour Signed URL field that appears will contain your digitally signed URL. Be sure to make a copy.
Generate digital signatures server-side
Compared to theSign a URL now widget, you will need to take a few additional actions when generating digital signatures server-side:
Strip off the protocol scheme and host portions of the URL, leaving only the path and the query:
The displayed URL signing secret is encoded in a modifiedBase64 for URLs.
As most cryptographic libraries require the key to be in raw byte format, you will likely need to decode your URL signing secret into its original raw format before signing.
- Sign the above stripped request using HMAC-SHA1.
As most cryptographic libraries generate a signature in raw byte format, you will need to convert the resulting binary signature using the modifiedBase64 for URLs to convert it into something that can be passed within the URL.
Note: Modified Base64 for URLs replaces the+and/characters of standard Base64 with-and_respectively, so that these Base64 no longer need to be URL-encoded.Append the Base64-encoded signature to the original unsigned request URL in the
signatureparameter. For example:https://maps.googleapis.com/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEY&signature=BASE64_SIGNATURE
/maps/api/staticmap?center=Z%C3%BCrich&size=400x400&key=YOUR_API_KEYFor samples showing ways to implement URL signing using server-side code, seeSample code for URL signing below.
Sample code for URL signing
The following sections show ways to implement URL signing usingserver-side code. URLs should always be signed server-side to avoidexposing your URL signing secret to users.
Python
The example below uses standard Python libraries to sign a URL. (Download the code.)
#!/usr/bin/python# -*- coding: utf-8 -*-""" Signs a URL using a URL signing secret """importhashlibimporthmacimportbase64importurllib.parseasurlparsedefsign_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 """ifnotinput_urlornotsecret:raiseException("Both input_url and secret are required")url=urlparse.urlparse(input_url)# We only need to sign the path+query part of the stringurl_to_sign=url.path+"?"+url.query# Decode the private key into its binary format# We need to decode the URL-encoded private keydecoded_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 URLencoded_signature=base64.urlsafe_b64encode(signature.digest())original_url=url.scheme+"://"+url.netloc+url.path+"?"+url.query# Return signed URLreturnoriginal_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
The example below uses thejava.util.Base64 class available since JDK 1.8 - older versions may need to use Apache Commons or similar. (Download the code.)
importjava.io.IOException;importjava.io.UnsupportedEncodingException;importjava.net.URI;importjava.net.URISyntaxException;importjava.security.InvalidKeyException;importjava.security.NoSuchAlgorithmException;importjava.util.Base64;// JDK 1.8 only - older versions may need to use Apache Commons or similar.importjavax.crypto.Mac;importjavax.crypto.spec.SecretKeySpec;importjava.net.URL;importjava.io.BufferedReader;importjava.io.InputStreamReader;publicclassUrlSigner{// Note: Generally, you should store your private key someplace safe// and read them into your codeprivatestaticStringkeyString="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.privatestaticStringurlString="YOUR_URL_TO_SIGN";// This variable stores the binary key, which is computed from the string (Base64) keyprivatestaticbyte[]key;publicstaticvoidmain(String[]args)throwsIOException,InvalidKeyException,NoSuchAlgorithmException,URISyntaxException{BufferedReaderinput=newBufferedReader(newInputStreamReader(System.in));StringinputUrl,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 itURLurl=newURL(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;}UrlSignersigner=newUrlSigner(inputKey);Stringrequest=signer.signRequest(url.getPath(),url.getQuery());System.out.println("Signed URL :"+url.getProtocol()+"://"+url.getHost()+request);}publicUrlSigner(StringkeyString)throwsIOException{// Convert the key from 'web safe' base 64 to binarykeyString=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);}publicStringsignRequest(Stringpath,Stringquery)throwsNoSuchAlgorithmException,InvalidKeyException,UnsupportedEncodingException,URISyntaxException{// Retrieve the proper URL components to signStringresource=path+'?'+query;// Get an HMAC-SHA1 signing key from the raw key bytesSecretKeySpecsha1Key=newSecretKeySpec(key,"HmacSHA1");// Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 keyMacmac=Mac.getInstance("HmacSHA1");mac.init(sha1Key);// compute the binary signature for the requestbyte[]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.Stringsignature=Base64.getEncoder().encodeToString(sigBytes);// convert the signature to 'web safe' base 64signature=signature.replace('+','-');signature=signature.replace('/','_');returnresource+"&signature="+signature;}}
Node JS
The example below uses native Node modules to sign a URL. (Download the code.)
Note:If you are using strict type checking:- In
decodeBase64Hash(code), change the type of the return value to{Buffer}. - In
encodeBase64Hash(key, data), change the type value ofkeyto{Buffer}.
'use strict'constcrypto=require('crypto');consturl=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} */functionremoveWebSafe(safeEncodedString){returnsafeEncodedString.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} */functionmakeWebSafe(encodedString){returnencodedString.replace(/\+/g,'-').replace(/\//g,'_');}/** * Takes a base64 code and decodes it. * * @param {string} code The encoded data. * @return {string} */functiondecodeBase64Hash(code){// "new Buffer(...)" is deprecated. Use Buffer.from if it exists.returnBuffer.from?Buffer.from(code,'base64'):newBuffer(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} */functionencodeBase64Hash(key,data){returncrypto.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} */functionsign(path,secret){consturi=url.parse(path);constsafeSecret=decodeBase64Hash(removeWebSafe(secret));consthashedSignature=makeWebSafe(encodeBase64Hash(safeSecret,uri.path));returnurl.format(uri)+'&signature='+hashedSignature;}
C#
The example below uses the defaultSystem.Security.Cryptography library to sign a URL request. Note that we need to convert the default Base64 encoding to implement a URL-safe version. (Download the code.)
usingSystem;usingSystem.Collections.Generic;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Web;namespaceSignUrl{publicstructGoogleSignedUrl{publicstaticstringSign(stringurl,stringkeyString){ASCIIEncodingencoding=newASCIIEncoding();// converting key to bytes will throw an exception, need to replace '-' and '_' characters first.stringusablePrivateKey=keyString.Replace("-","+").Replace("_","/");byte[]privateKeyBytes=Convert.FromBase64String(usablePrivateKey);Uriuri=newUri(url);byte[]encodedPathAndQueryBytes=encoding.GetBytes(uri.LocalPath+uri.Query);// compute the hashHMACSHA1algorithm=newHMACSHA1(privateKeyBytes);byte[]hash=algorithm.ComputeHash(encodedPathAndQueryBytes);// convert the bytes to string and make url-safe by replacing '+' and '/' charactersstringsignature=Convert.ToBase64String(hash).Replace("+","-").Replace("/","_");// Add the signature to the existing URI.returnuri.Scheme+"://"+uri.Host+uri.LocalPath+uri.Query+"&signature="+signature;}}classProgram{staticvoidMain(){// Note: Generally, you should store your private key someplace safe// and read them into your codeconststringkeyString="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.conststringurlString="YOUR_URL_TO_SIGN";stringinputUrl=null;stringinputKey=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));}}}
Examples in additional languages
Examples that cover more languages are available in theurl-signing project.
Troubleshooting
Important: Verify that the used URL signing secret and API key are from the same Google Cloud project.If the request includes an invalid signature, the API returns anHTTP 403 (Forbidden) error. This error most likely occurs if the used signing secret isn't linked to the passed API key, or if non-ASCII input isn't URL-encodedbefore signing.
To troubleshoot the issue, copy the request URL, strip thesignature query parameter, and regenerate a valid signature following the instructions below:
To generate a digital signature with an API key using theSign a URL now widget in the Google Cloud console:
- Locate theSign a URL now widget, as described inStep 1: Get your URL signing secret.
- In theURL field, paste your unsigned request URL fromStep 2: Construct your unsigned request.
- TheYour Signed URL field that appears will contain your digitally signed URL. Be sure to make a copy.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-11-21 UTC.