|
| 1 | +# Copyright 2015 Google Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +Sample Google App Engine application that demonstrates using the App Engine |
| 17 | +identity API to generate an auth token. |
| 18 | +
|
| 19 | +For more information about App Engine, see README.md under /appengine. |
| 20 | +""" |
| 21 | + |
| 22 | +# [START all] |
| 23 | +import json |
| 24 | +import logging |
| 25 | + |
| 26 | +from google.appengine.api import app_identity |
| 27 | +from google.appengine.api import urlfetch |
| 28 | +import webapp2 |
| 29 | + |
| 30 | + |
| 31 | +class MainPage(webapp2.RequestHandler): |
| 32 | + def get(self): |
| 33 | + auth_token, _ = app_identity.get_access_token( |
| 34 | + 'https://www.googleapis.com/auth/cloud-platform') |
| 35 | + logging.info( |
| 36 | + 'Using token {} to represent identity {}'.format( |
| 37 | + auth_token, app_identity.get_service_account_name())) |
| 38 | + |
| 39 | + response = urlfetch.fetch( |
| 40 | + 'https://www.googleapis.com/storage/v1/b?project={}'.format( |
| 41 | + app_identity.get_application_id()), |
| 42 | + method=urlfetch.GET, |
| 43 | + headers={ |
| 44 | + 'Authorization': 'Bearer {}'.format(auth_token) |
| 45 | + } |
| 46 | + ) |
| 47 | + |
| 48 | + if response.status_code != 200: |
| 49 | + raise Exception( |
| 50 | + 'Call failed. Status code {}. Body {}'.format( |
| 51 | + response.status_code, response.content)) |
| 52 | + |
| 53 | + result = json.loads(response.content) |
| 54 | + self.response.headers['Content-Type'] = 'application/json' |
| 55 | + self.response.write(json.dumps(result, indent=2)) |
| 56 | + |
| 57 | +app = webapp2.WSGIApplication([ |
| 58 | + ('/', MainPage) |
| 59 | +], debug=True) |
| 60 | + |
| 61 | +# [END all] |
0 commit comments