8000 Endpoints Auth Cleanup (#1988) · devlance/python-docs-samples@5456742 · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 5456742

Browse files
Endpoints Auth Cleanup (GoogleCloudPlatform#1988)
Endpoints: cleaned up service-to-service auth samples
1 parent 1f14fff commit 5456742

File tree

2 files changed

+43
-40
lines changed

2 files changed

+43
-40
lines changed

endpoints/getting-started/clients/google-jwt-client.py

Lines changed: 39 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -22,65 +22,56 @@
2222

2323
import google.auth.crypt
2424
import google.auth.jwt
25-
import requests
26-
from six.moves import urllib
2725

26+
import requests
2827

29-
def generate_jwt(service_account_file):
30-
"""Generates a signed JSON Web Token using a Google API Service Account."""
3128

32-
# Note: this sample shows how to manually create the JWT for the purposes
33-
# of showing how the authentication works, but you can use
34-
# google.auth.jwt.Credentials to automatically create the JWT.
35-
# http://google-auth.readthedocs.io/en/latest/reference
36-
# /google.auth.jwt.html#google.auth.jwt.Credentials
29+
# [START endpoints_generate_jwt_sa]
30+
def generate_jwt(sa_keyfile,
31+
sa_email='account@project-id.iam.gserviceaccount.com',
32+
audience='your-service-name',
33+
expiry_length=3600):
3734

38-
signer = google.auth.crypt.RSASigner.from_service_account_file(
39-
service_account_file)
35+
"""Generates a signed JSON Web Token using a Google API Service Account."""
4036

4137
now = int(time.time())
42-
expires = now + 3600 # One hour in seconds
4338

39+
# build payload
4440
payload = {
4541
'iat': now,
46-
'exp': expires,
47-
# aud must match 'audience' in the security configuration in your
48-
# swagger spec. It can be any string.
49-
'aud': 'echo.endpoints.sample.google.com',
42+
# expires after 'expirary_length' seconds.
43+
"exp": now + expiry_length,
5044
# iss must match 'issuer' in the security configuration in your
5145
# swagger spec (e.g. service account email). It can be any string.
52-
'iss': 'jwt-client.endpoints.sample.google.com',
53-
# sub and email are mapped to the user id and email respectively.
54-
# sub should match 'iss'
55-
'sub': 'jwt-client.endpoints.sample.google.com',
56-
'email': 'user@example.com'
46+
'iss': sa_email,
47+
# aud must be either your Endpoints service name, or match the value
48+
# specified as the 'x-google-audience' in the OpenAPI document.
49+
'aud': audience,
50+
# sub and email should match the service account's email address
51+
'sub': sa_email,
52+
'email': sa_email
5753
}
5854

59-
jwt = google.auth.jwt.encode(signer, payload).decode('UTF-8')
55+
# sign with keyfile
56+
signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
57+
jwt = google.auth.jwt.encode(signer, payload)
6058

6159
return jwt
60+
# [END endpoints_generate_jwt_sa]
6261

6362

64-
def make_request(host, api_key, signed_jwt):
65-
"""Makes a request to the auth info endpoint for Google JWTs."""
66-
url = urllib.parse.urljoin(host, '/auth/info/googlejwt')
67-
params = {
68-
'key': api_key
69-
}
63+
# [START endpoints_jwt_request]
64+
def make_jwt_request(signed_jwt, url='https://your-endpoint.com'):
65+
"""Makes an authorized request to the endpoint"""
7066
headers = {
71-
'Authorization': 'Bearer {}'.format(signed_jwt)
67+
'Authorization': 'Bearer {}'.format(signed_jwt),
68+
'content-type': 'application/json'
7269
}
73-
74-
response = requests.get(url, params=params, headers=headers)
70+
response = requests.get(url, headers=headers)
7571

7672
response.raise_for_status()
7773
return response.text
78-
79-
80-
def main(host, api_key, service_account_file):
81-
signed_jwt = generate_jwt(service_account_file)
82-
response = make_request(host, api_key, signed_jwt)
83-
print(response)
74+
# [END endpoints_jwt_request]
8475

8576

8677
if __name__ == '__main__':
@@ -90,11 +81,19 @@ def main(host, api_key, service_account_file):
9081
parser.add_argument(
9182
'host', help='Your API host, e.g. https://your-project.appspot.com.')
9283
parser.add_argument(
93-
'api_key', help='Your API key.')
84+
'audience', help='The aud entry for the JWT')
9485
parser.add_argument(
95-
'service_account_file',
86+
'sa_path',
9687
help='The path to your service account json file.')
88+
parser.add_argument(
89+
'sa_email',
90+
help='The email address for the service account.')
9791

9892
args = parser.parse_args()
9993

100-
main(args.host, args.api_key, args.service_account_file)
94+
expiry_length = 3600
95+
keyfile_jwt = generate_jwt(args.sa_path,
96+
args.sa_email,
97+
args.audience,
98+
expiry_length)
99+
print(make_jwt_request(keyfile_jwt, args.host))

endpoints/getting-started/main.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@
2323
import logging
2424

2525
from flask import Flask, jsonify, request
26+
2627
from flask_cors import cross_origin
28+
2729
from six.moves import http_client
2830

2931

@@ -45,6 +47,7 @@ def echo():
4547
return jsonify({'message': message})
4648

4749

50+
# [START endpoints_auth_info_backend]
4851
def auth_info():
4952
"""Retrieves the authenication information from Google Cloud Endpoints."""
5053
encoded_info = request.headers.get('X-Endpoint-API-UserInfo', None)
@@ -56,6 +59,7 @@ def auth_info():
5659
user_info = {'id': 'anonymous'}
5760

5861
return jsonify(user_info)
62+
# [START endpoints_auth_info_backend]
5963

6064

6165
@app.route('/auth/info/googlejwt', methods=['GET'])

0 commit comments

Comments
 (0)
0