dummy-server/app.py
2024-06-27 18:55:08 +02:00

68 lines
2.1 KiB
Python

import jwt
from flask import Flask, request, render_template
app = Flask(__name__)
idp_url = "https://id.vilanet.fr/realms/vilanet"
client_id = "dummy-server"
def api(required_role):
callback_url = False
auth_error = "No user identified"
token_data = {}
# is it OK to use access token to check API authorization on server side
# it is not OK to use ID token to check API authorization on server side
access_token = False
if 'access_token' in request.cookies:
access_token = request.cookies['access_token']
elif 'Authorization' in request.headers:
bearer = request.headers['Authorization']
if bearer.startswith("Bearer "):
access_token = bearer[7:]
if access_token:
jwks_uri = f"{idp_url}/protocol/openid-connect/certs"
jwks_client = jwt.PyJWKClient(jwks_uri)
key = jwks_client.get_signing_key_from_jwt(access_token)
try:
token_data = jwt.decode(
access_token,
key.key,
algorithms=["RS256"],
audience=client_id,
options={'verify_signature': True, 'verify_aud': True}
)
auth_error = f'Missing required role "{required_role}"'
if 'resource_access' in token_data:
if client_id in token_data['resource_access']:
if 'roles' in token_data['resource_access'][client_id]:
if required_role in token_data['resource_access'][client_id]['roles']:
auth_error = False
except Exception as e:
auth_error = e
if 'callbackUrl' in request.args:
callback_url = request.args['callbackUrl']
return render_template(
'index.html',
callback_url=callback_url,
auth_error=auth_error,
token_data=token_data
)
@app.route("/api/v1/service1")
def api_service1():
return api("service1-invoke")
@app.route("/api/v1/service2")
def api_service2():
return api("service2-invoke")
if __name__ == "__main__":
app.run(host='127.0.0.1', port=5002, debug=True)