-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added three samples: 1. Use App Engine default service account client (without key file). 2. Use non-default service account client (without key file). 3. Use Google ID token client (without key file)
- Loading branch information
Showing
10 changed files
with
410 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
appengine/flexible/endpoints/clients/service_to_service_gae_default/app.yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
runtime: python27 | ||
api_version: 1 | ||
threadsafe: true | ||
|
||
handlers: | ||
- url: /.* | ||
script: main.app |
82 changes: 82 additions & 0 deletions
82
appengine/flexible/endpoints/clients/service_to_service_gae_default/main.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
# Copyright 2016 Google Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0(the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http: // www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Example of calling a Google Cloud Endpoint API with a JWT signed by | ||
Google App Engine Default Service Account.""" | ||
|
||
import base64 | ||
import httplib | ||
import json | ||
import time | ||
|
||
import webapp2 | ||
|
||
from google.appengine.api import app_identity | ||
|
||
DEFAUTL_SERVICE_ACCOUNT = '[email protected]' | ||
HOST = "YOUR-SERVER-PROJECT-ID.appspot.com" | ||
|
||
|
||
def generate_jwt(): | ||
"""Generates a signed JSON Web Token using the Google App Engine default | ||
service account.""" | ||
now = int(time.time()) | ||
|
||
header_json = json.dumps({ | ||
"typ": "JWT", | ||
"alg": "RS256"}) | ||
|
||
payload_json = json.dumps({ | ||
'iat': now, | ||
#expires after one hour. | ||
"exp": now + 3600, | ||
#iss is the Google App Engine default service account email. | ||
'iss': DEFAUTL_SERVICE_ACCOUNT, | ||
'sub': DEFAUTL_SERVICE_ACCOUNT, | ||
#aud must match 'audience' in the security configuration in your | ||
#swagger spec.It can be any string. | ||
'aud': 'echo.endpoints.sample.google.com', | ||
"email": DEFAUTL_SERVICE_ACCOUNT | ||
}) | ||
|
||
headerAndPayload = '{}.{}'.format(base64.urlsafe_b64encode(header_json), | ||
base64.urlsafe_b64encode(payload_json)) | ||
(key_name, signature) = app_identity.sign_blob(headerAndPayload) | ||
signed_jwt = '{}.{}'.format(headerAndPayload, | ||
base64.urlsafe_b64encode(signature)) | ||
|
||
return signed_jwt | ||
|
||
|
||
def make_request(signed_jwt): | ||
"""Makes a request to the auth info endpoint for Google JWTs.""" | ||
headers = {'Authorization': 'Bearer {}'.format(signed_jwt)} | ||
conn = httplib.HTTPSConnection(HOST) | ||
conn.request("GET", '/auth/info/googlejwt', None, headers) | ||
res = conn.getresponse() | ||
conn.close() | ||
return res.read() | ||
|
||
|
||
class MainPage(webapp2.RequestHandler): | ||
def get(self): | ||
self.response.headers['Content-Type'] = 'text/plain' | ||
signed_jwt = generate_jwt() | ||
res = make_request(signed_jwt) | ||
self.response.write(res) | ||
|
||
|
||
app = webapp2.WSGIApplication([ | ||
('/', MainPage), | ||
], debug=True) |
7 changes: 7 additions & 0 deletions
7
appengine/flexible/endpoints/clients/service_to_service_google_id_token/app.yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
runtime: python27 | ||
api_version: 1 | ||
threadsafe: true | ||
|
||
handlers: | ||
- url: /.* | ||
script: main.app |
97 changes: 97 additions & 0 deletions
97
appengine/flexible/endpoints/clients/service_to_service_google_id_token/main.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
# Copyright 2016 Google Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0(the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http: // www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Example of calling a Google Cloud Endpoint API from Google App Engine | ||
Default Service Account using Google ID token.""" | ||
|
||
import base64 | ||
import httplib | ||
import json | ||
import time | ||
import urllib | ||
|
||
import webapp2 | ||
|
||
from google.appengine.api import app_identity | ||
|
||
DEFAUTL_SERVICE_ACCOUNT = "[email protected]" | ||
HOST = "YOUR-SERVER-PROJECT-ID.appspot.com" | ||
TARGET_AUD = "[email protected]" | ||
|
||
|
||
def generate_jwt(): | ||
"""Generates a signed JSON Web Token using the Google App Engine default | ||
service account.""" | ||
now = int(time.time()) | ||
|
||
header_json = json.dumps({ | ||
"typ": "JWT", | ||
"alg": "RS256"}) | ||
|
||
payload_json = json.dumps({ | ||
"iat": now, | ||
# expires after one hour. | ||
"exp": now + 3600, | ||
# iss is the Google App Engine default service account email. | ||
"iss": DEFAUTL_SERVICE_ACCOUNT, | ||
# scope must match 'audience' for google_id_token in the security | ||
# configuration in your swagger spec. | ||
"scope": TARGET_AUD, | ||
# aud must be Google token endpoints URL. | ||
"aud": "https://www.googleapis.com/oauth2/v4/token" | ||
}) | ||
|
||
headerAndPayload = '{}.{}'.format(base64.urlsafe_b64encode(header_json), | ||
base64.urlsafe_b64encode(payload_json)) | ||
(key_name, signature) = app_identity.sign_blob(headerAndPayload) | ||
signed_jwt = '{}.{}'.format(headerAndPayload, | ||
base64.urlsafe_b64encode(signature)) | ||
|
||
return signed_jwt | ||
|
||
|
||
def get_id_token(): | ||
"""Request a Google ID token using a JWT.""" | ||
params = urllib.urlencode({ | ||
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', | ||
'assertion': generate_jwt()}) | ||
headers = {"Content-Type": "application/x-www-form-urlencoded"} | ||
conn = httplib.HTTPSConnection("www.googleapis.com") | ||
conn.request("POST", "/oauth2/v4/token", params, headers) | ||
res = json.loads(conn.getresponse().read()) | ||
conn.close() | ||
return res['id_token'] | ||
|
||
|
||
def make_request(token): | ||
"""Makes a request to the auth info endpoint for Google ID token.""" | ||
headers = {'Authorization': 'Bearer {}'.format(token)} | ||
conn = httplib.HTTPSConnection(HOST) | ||
conn.request("GET", '/auth/info/googleidtoken', None, headers) | ||
res = conn.getresponse() | ||
conn.close() | ||
return res.read() | ||
|
||
|
||
class MainPage(webapp2.RequestHandler): | ||
def get(self): | ||
self.response.headers['Content-Type'] = 'text/plain' | ||
token = get_id_token() | ||
res = make_request(token) | ||
self.response.write(res) | ||
|
||
|
||
app = webapp2.WSGIApplication([ | ||
('/', MainPage), | ||
], debug=True) |
7 changes: 7 additions & 0 deletions
7
appengine/flexible/endpoints/clients/service_to_service_non_default/app.yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
runtime: python27 | ||
api_version: 1 | ||
threadsafe: true | ||
|
||
handlers: | ||
- url: /.* | ||
script: main.app |
3 changes: 3 additions & 0 deletions
3
appengine/flexible/endpoints/clients/service_to_service_non_default/appengine_config.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from google.appengine.ext import vendor | ||
|
||
vendor.add('lib') |
93 changes: 93 additions & 0 deletions
93
appengine/flexible/endpoints/clients/service_to_service_non_default/main.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
# Copyright 2016 Google Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0(the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http: // www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Example of calling a Google Cloud Endpoint API with a JWT signed by a | ||
Service Account.""" | ||
|
||
import base64 | ||
import httplib | ||
import json | ||
import time | ||
|
||
from googleapiclient.discovery import build | ||
import httplib2 | ||
from oauth2client.contrib.appengine import AppAssertionCredentials | ||
import webapp2 | ||
|
||
SERVICE_ACCOUNT_EMAIL = "YOUR-SERVICE-ACCOUNT-EMAIL" | ||
HOST = "YOUR-SERVER-PROJECT-ID.appspot.com" | ||
SERVICE_ACCOUNT = \ | ||
"projects/YOUR-CLIENT-PROJECT-ID/serviceAccounts/YOUR-SERVICE-ACCOUNT-EMAIL" | ||
|
||
|
||
def generate_jwt(): | ||
"""Generates a signed JSON Web Token using a service account.""" | ||
credentials = AppAssertionCredentials( | ||
'https://www.googleapis.com/auth/iam') | ||
http_auth = credentials.authorize(httplib2.Http()) | ||
service = build(serviceName='iam', version='v1', http=http_auth) | ||
|
||
now = int(time.time()) | ||
|
||
header_json = json.dumps({ | ||
"typ": "JWT", | ||
"alg": "RS256"}) | ||
|
||
payload_json = json.dumps({ | ||
'iat': now, | ||
# expires after one hour. | ||
"exp": now + 3600, | ||
# iss is the service account email. | ||
'iss': SERVICE_ACCOUNT_EMAIL, | ||
'sub': SERVICE_ACCOUNT_EMAIL, | ||
# aud must match 'audience' in the security configuration in your | ||
# swagger spec.It can be any string. | ||
'aud': 'echo.endpoints.sample.google.com', | ||
"email": SERVICE_ACCOUNT_EMAIL | ||
}) | ||
|
||
headerAndPayload = '{}.{}'.format(base64.urlsafe_b64encode(header_json), | ||
base64.urlsafe_b64encode(payload_json)) | ||
slist = service.projects().serviceAccounts().signBlob( | ||
name=SERVICE_ACCOUNT, | ||
body={'bytesToSign': base64.b64encode(headerAndPayload)}) | ||
res = slist.execute() | ||
signature = base64.urlsafe_b64encode( | ||
base64.decodestring(res['signature'])) | ||
signed_jwt = '{}.{}'.format(headerAndPayload, signature) | ||
|
||
return signed_jwt | ||
|
||
|
||
def make_request(signed_jwt): | ||
"""Makes a request to the auth info endpoint for Google JWTs.""" | ||
headers = {'Authorization': 'Bearer {}'.format(signed_jwt)} | ||
conn = httplib.HTTPSConnection(HOST) | ||
conn.request("GET", '/auth/info/googlejwt', None, headers) | ||
res = conn.getresponse() | ||
conn.close() | ||
return res.read() | ||
|
||
|
||
class MainPage(webapp2.RequestHandler): | ||
def get(self): | ||
self.response.headers['Content-Type'] = 'text/plain' | ||
signed_jwt = generate_jwt() | ||
res = make_request(signed_jwt) | ||
self.response.write(res) | ||
|
||
|
||
app = webapp2.WSGIApplication([ | ||
('/', MainPage), | ||
], debug=True) |
Oops, something went wrong.