Files
connexion/examples/jwt/app.py
Robbe Sneyders 073f0d446e Update examples for Connexion 3.0 (#1615)
This PR updates the examples for Connexion 3.0 and merges them for
OpenAPI and Swagger.

2 examples required some changes to make them work:
- The reverse proxy example required some fixes to the
SwaggerUIMiddleware to leverage the `root_path` correctly. This is
included in the PR.
- The enforced defaults example requires the json validator to adapt the
body and pass it on. We currently pass on the original body after
validation, and I'm not sure if we should change this. I'll submit a
separate PR to discuss this.
2022-12-30 20:34:19 +01:00

55 lines
1.2 KiB
Python
Executable File

"""
Basic example of a resource server
"""
import time
from pathlib import Path
import connexion
from jose import JWTError, jwt
from werkzeug.exceptions import Unauthorized
JWT_ISSUER = "com.zalando.connexion"
JWT_SECRET = "change_this"
JWT_LIFETIME_SECONDS = 600
JWT_ALGORITHM = "HS256"
def generate_token(user_id):
timestamp = _current_timestamp()
payload = {
"iss": JWT_ISSUER,
"iat": int(timestamp),
"exp": int(timestamp + JWT_LIFETIME_SECONDS),
"sub": str(user_id),
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def decode_token(token):
try:
return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
except JWTError as e:
raise Unauthorized from e
def get_secret(user, token_info) -> str:
return """
You are user_id {user} and the secret is 'wbevuec'.
Decoded token claims: {token_info}.
""".format(
user=user, token_info=token_info
)
def _current_timestamp() -> int:
return int(time.time())
app = connexion.FlaskApp(__name__, specification_dir="spec")
app.add_api("openapi.yaml")
if __name__ == "__main__":
app.run(f"{Path(__file__).stem}:app", port=8080)