|
17 | 17 |
|
18 | 18 | from flask import Flask
|
19 | 19 |
|
| 20 | +import google.auth |
| 21 | +import google.auth.transport.requests |
| 22 | +from google.oauth2 import service_account |
| 23 | +import google.oauth2._client |
| 24 | +import google.oauth2.id_token |
| 25 | +import requests_toolbelt.adapters.appengine |
| 26 | + |
| 27 | +# Use the App Engine Requests adapter. This makes sure that Requests uses |
| 28 | +# URLFetch. |
| 29 | +requests_toolbelt.adapters.appengine.monkeypatch() |
| 30 | + |
20 | 31 |
|
21 | 32 | app = Flask(__name__)
|
22 | 33 |
|
23 | 34 |
|
| 35 | +def get_open_id_connect_id_token(): |
| 36 | + credentials = service_account.Credentials.from_service_account_file( |
| 37 | + 'service-account.json', |
| 38 | + additional_claims={ |
| 39 | + 'target_audience': 'https://msachs-staging.appspot.com' |
| 40 | + }) |
| 41 | + |
| 42 | + grant_assertion = credentials._make_authorization_grant_assertion() |
| 43 | + |
| 44 | + request = google.auth.transport.requests.Request() |
| 45 | + |
| 46 | + # oauth2._client.jwt_grant (rightfully) expects an access token |
| 47 | + # in the response, but the target_audience claim doesn't return one. |
| 48 | + # so use the underlying _token_endpoint_request instead. |
| 49 | + |
| 50 | + body = { |
| 51 | + 'assertion': grant_assertion, |
| 52 | + 'grant_type': google.oauth2._client._JWT_GRANT_TYPE, |
| 53 | + } |
| 54 | + |
| 55 | + token_response = google.oauth2._client._token_endpoint_request( |
| 56 | + request, credentials._token_uri, body) |
| 57 | + |
| 58 | + return token_response['id_token'] |
| 59 | + |
| 60 | + |
| 61 | +def verify_open_id_connect_id_token(id_token): |
| 62 | + certs_url = 'https://www.googleapis.com/oauth2/v1/certs' |
| 63 | + request = google.auth.transport.requests.Request() |
| 64 | + |
| 65 | + claims = google.oauth2.id_token.verify_token( |
| 66 | + id_token, request, certs_url=certs_url) |
| 67 | + |
| 68 | + return claims |
| 69 | + |
| 70 | + |
24 | 71 | @app.route('/')
|
25 | 72 | def hello():
|
26 |
| - return 'Hello World!' |
| 73 | + id_token = get_open_id_connect_id_token() |
| 74 | + claims = verify_open_id_connect_id_token(id_token) |
| 75 | + return 'Token: {}, Claims: {}'.format(id_token, claims) |
27 | 76 |
|
28 | 77 |
|
29 | 78 | @app.errorhandler(500)
|
|
0 commit comments