Google API Key Constraint Called from Fetch URL in Engine Application

I have an API key for the Google API that I would like to use in all my requests. Some of these requests will come from a Google App Engine application (Python 2.7). I planned to use the UrlFetch library to complete the POST request, basically as follows:

headers = {'Content-Type': 'application/json'} payload = {'longUrl': request.long_url} result = urlfetch.fetch([API_REQUEST_URL], method=urlfetch.POST, payload=json.dumps(payload), headers=headers) json_result = json.loads(result.content) 

I set the referrer restriction on my API key to *.[my-app].appspot.com/* with the hope that this will protect my API key from unauthorized use and deny the need to update the restriction based on IP addresses (since App Engine IPs change all the time).

This approach did not help me, because it seems that urlfetch does NOT set the value for referrer on its own. I suppose I can add my own referrer, but then someone else could. This approach is not very safe.

What is the best practice? How do I restrict the key, given that I am using urlfetch from App Engine? If I use the HTTP Referrer restriction, what address do I use?

Thank you very much.

+5
source share
2 answers

As you noticed, the referrer header can be falsified, so setting a referrer restriction on your API key is useless to start with.

But you can add validation based on the X-Appengine-Inbound-Appid , which is cleared by the GAE framework and accurately defines the application. From Issuing a Request to Another App Engine Application :

When sending a request to another App Engine application, the App Engine application must assert its identity by adding the X-Appengine-Inbound-Appid to the request. If you provide the Retrieve Service URL so that you do not follow redirects, App Engine will add this header for requests automatically.

To tell the Fetch URL service not to follow redirects, set the fetch follow_redirects parameter to False .

Note If you are making requests to another App Engine application, use its name appspot.com , not the custom domain for your application.

+1
source

Did you get this error message?

 Requests from referer <empty> are blocked. 

urlfetch doesn't seem to attach Refer automatically, so you should set Refer to your request header.

 headers = {'Content-Type': 'application/json','Referer': '*.[my-app].appspot.com/*'} 
+1
source

Source: https://habr.com/ru/post/1258647/


All Articles