27
27
import requests
28
28
29
29
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.
32
33
33
34
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.
38
40
39
41
Returns:
40
42
(user_id, user_email, error_str).
41
43
"""
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 ):
42
72
try :
43
73
key_id = jwt .get_unverified_header (iap_jwt ).get ('kid' )
44
74
if not key_id :
@@ -47,7 +77,7 @@ def validate_iap_jwt(base_url, iap_jwt):
47
77
decoded_jwt = jwt .decode (
48
78
iap_jwt , key ,
49
79
algorithms = ['ES256' ],
50
- audience = base_url )
80
+ audience = expected_audience )
51
81
return (decoded_jwt ['sub' ], decoded_jwt ['email' ], '' )
52
82
except (jwt .exceptions .InvalidTokenError ,
53
83
requests .exceptions .RequestException ) as e :
0 commit comments