-
Notifications
You must be signed in to change notification settings - Fork 39
/
app.py
71 lines (52 loc) · 1.85 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from flask import Flask, render_template, request
from flask_cors import CORS, cross_origin
import os
import requests
import json
import time
import sys
import boto3
from datetime import datetime
import jwt
import base64
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/')
@cross_origin()
def index():
response = ""
region = os.environ.get('AWS_REGION')
response +='<body text="blue" bgcolor="white"><head> <title>Yelb Sample Application </title> </head>'
response += "<h2>User Identity Data from ALB / Cognito Integrated Authentication </h2> <hr/>"
try:
headers = dict(request.headers)
encoded_jwt=""
for k, v in headers.items():
if k == 'X-Amzn-Oidc-Data':
encoded_jwt=v
break
# Step 1: Get the key id from JWT headers (the kid field)
jwt_headers = encoded_jwt.split('.')[0]
decoded_jwt_headers = base64.b64decode(jwt_headers)
decoded_jwt_headers = decoded_jwt_headers.decode("utf-8")
decoded_json = json.loads(decoded_jwt_headers)
kid = decoded_json['kid']
# Step 2: Get the public key from regional endpoint
url = 'https://public-keys.auth.elb.' + region + '.amazonaws.com/' + kid
req = requests.get(url)
pub_key = req.text
# Step 3: Get the payload
payload = jwt.decode(encoded_jwt, pub_key, algorithms=['ES256'])
sub = payload['sub']
email = payload['email']
response += '<p style="color:green;"><b>'
response += "sub={} <br />".format(sub)
response += "email={} <br />".format(email)
except Exception as e:
print(e)
response += "\n error={} \n". format(str(e))
return response
if __name__ == '__main__':
print("Starting A Simple Web Service ...")
app.run(port=80,host='0.0.0.0')