2727import requests
2828
2929
30- def validate_iap_jwt (base_url , iap_jwt ):
31- """Validate a JWT passed to your application by Identity-Aware Proxy.
30+ def validate_iap_jwt_from_app_engine (iap_jwt , cloud_project_number ,
31+ cloud_project_id ):
32+ """Validate a JWT passed to your App Engine app by Identity-Aware Proxy.
3233
3334 Args:
34- base_url: The URL from the incoming request, minus any path, query, etc.
35- For instance: "https://example.com:8443" or
36- "https://example.appspot.com" .
37- iap_jwt: The contents of the X-Goog-Authenticated-User-JWT header.
35+ iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header.
36+ cloud_project_number: The project *number* for your Google Cloud project.
37+ This is returned by 'gcloud projects describe $PROJECT_ID', or
38+ in the Project Info card in Cloud Console.
39+ cloud_project_id: The project *ID* for your Google Cloud project.
3840
3941 Returns:
4042 (user_id, user_email, error_str).
4143 """
44+ expected_audience = '/projects/{}/apps/{}' .format (
45+ cloud_project_number , cloud_project_id )
46+ return _validate_iap_jwt (iap_jwt , expected_audience )
47+
48+
49+ def validate_iap_jwt_from_compute_engine (iap_jwt , cloud_project_number ,
50+ backend_service_id ):
51+ """Validate an IAP JWT for your (Compute|Container) Engine service.
52+
53+ Args:
54+ iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header.
55+ cloud_project_number: The project *number* for your Google Cloud project.
56+ This is returned by 'gcloud projects describe $PROJECT_ID', or
57+ in the Project Info card in Cloud Console.
58+ backend_service_id: The ID of the backend service used to access the
59+ application. See
60+ https://cloud.google.com/iap/docs/signed-headers-howto
61+ for details on how to get this value.
62+
63+ Returns:
64+ (user_id, user_email, error_str).
65+ """
66+ expected_audience = '/projects/{}/global/backendServices/{}' .format (
67+ cloud_project_number , backend_service_id )
68+ return _validate_iap_jwt (iap_jwt , expected_audience )
69+
70+
71+ def _validate_iap_jwt (iap_jwt , expected_audience ):
4272 try :
4373 key_id = jwt .get_unverified_header (iap_jwt ).get ('kid' )
4474 if not key_id :
@@ -47,7 +77,7 @@ def validate_iap_jwt(base_url, iap_jwt):
4777 decoded_jwt = jwt .decode (
4878 iap_jwt , key ,
4979 algorithms = ['ES256' ],
50- audience = base_url )
80+ audience = expected_audience )
5181 return (decoded_jwt ['sub' ], decoded_jwt ['email' ], '' )
5282 except (jwt .exceptions .InvalidTokenError ,
5383 requests .exceptions .RequestException ) as e :
0 commit comments