|
16 | 16 | Demonstrates how to send authenticated service-to-service requests, eg
|
17 | 17 | for Cloud Run or Cloud Functions"""
|
18 | 18 |
|
19 |
| -# [START google_auth_idtoken_serverless] |
20 | 19 | # [START functions_bearer_token]
|
21 | 20 | # [START cloudrun_service_to_service_auth]
|
22 |
| -# [START run_service_to_service_auth] |
23 | 21 | import urllib
|
24 | 22 |
|
25 | 23 | import google.auth.transport.requests
|
26 | 24 | import google.oauth2.id_token
|
27 | 25 |
|
28 | 26 |
|
29 |
| -def make_authorized_get_request(service_url): |
| 27 | +def make_authorized_get_request(service_url, audience): |
30 | 28 | """
|
31 | 29 | make_authorized_get_request makes a GET request to the specified HTTP endpoint
|
32 |
| - in service_url (must be a complete URL) by authenticating with the |
33 |
| - ID token obtained from the google-auth client library. |
| 30 | + by authenticating with the ID token obtained from the google-auth client library |
| 31 | + using the specified audience value. |
34 | 32 | """
|
35 | 33 |
|
| 34 | + # [END functions_bearer_token] |
| 35 | + # Cloud Run uses your service's hostname as the `audience` value |
| 36 | + # audience = 'https://my-cloud-run-service.run.app/' |
| 37 | + # [END cloudrun_service_to_service_auth] |
| 38 | + |
| 39 | + # [START functions_bearer_token] |
| 40 | + # Cloud Functions uses your function's URL as the `audience` value |
| 41 | + # audience = https://project-region-projectid.cloudfunctions.net/myFunction |
| 42 | + # [START cloudrun_service_to_service_auth] |
| 43 | + |
36 | 44 | req = urllib.request.Request(service_url)
|
37 | 45 |
|
38 | 46 | auth_req = google.auth.transport.requests.Request()
|
39 |
| - id_token = google.oauth2.id_token.fetch_id_token(auth_req, service_url) |
| 47 | + id_token = google.oauth2.id_token.fetch_id_token(auth_req, audience) |
40 | 48 |
|
41 | 49 | req.add_header("Authorization", f"Bearer {id_token}")
|
42 | 50 | response = urllib.request.urlopen(req)
|
43 | 51 |
|
44 | 52 | return response.read()
|
45 |
| -# [END run_service_to_service_auth] |
46 | 53 | # [END cloudrun_service_to_service_auth]
|
47 | 54 | # [END functions_bearer_token]
|
48 |
| -# [END google_auth_idtoken_serverless] |
|
0 commit comments