|
| 1 | +from datetime import datetime |
| 2 | +from datetime import timedelta |
| 3 | +from datetime import timezone |
| 4 | + |
| 5 | +from flask import Flask |
| 6 | +from flask import jsonify |
| 7 | + |
| 8 | +from flask_jwt_extended import create_access_token |
| 9 | +from flask_jwt_extended import get_jwt |
| 10 | +from flask_jwt_extended import get_jwt_identity |
| 11 | +from flask_jwt_extended import jwt_required |
| 12 | +from flask_jwt_extended import JWTManager |
| 13 | +from flask_jwt_extended import set_access_cookies |
| 14 | +from flask_jwt_extended import unset_jwt_cookies |
| 15 | + |
| 16 | +app = Flask(__name__) |
| 17 | + |
| 18 | +# If true this will only allow the cookies that contain your JWTs to be sent |
| 19 | +# over https. In production, this should always be set to True |
| 20 | +app.config["JWT_COOKIE_SECURE"] = False |
| 21 | +app.config["JWT_TOKEN_LOCATION"] = ["cookies"] |
| 22 | +app.config["JWT_SECRET_KEY"] = "super-secret" # Change this in your code! |
| 23 | +app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1) |
| 24 | + |
| 25 | +jwt = JWTManager(app) |
| 26 | + |
| 27 | + |
| 28 | +# Using an `after_request` callback, we refresh any token that is within 30 |
| 29 | +# minutes of expiring. Change the timedeltas to match the needs of your application. |
| 30 | +@app.after_request |
| 31 | +def refresh_expiring_jwts(response): |
| 32 | + try: |
| 33 | + exp_timestamp = get_jwt()["exp"] |
| 34 | + now = datetime.now(timezone.utc) |
| 35 | + target_timestamp = datetime.timestamp(now + timedelta(minutes=30)) |
| 36 | + if target_timestamp > exp_timestamp: |
| 37 | + access_token = create_access_token(identity=get_jwt_identity()) |
| 38 | + set_access_cookies(response, access_token) |
| 39 | + return response |
| 40 | + except (RuntimeError, KeyError): |
| 41 | + # Case where there is not a valid JWT. Just return the original respone |
| 42 | + return response |
| 43 | + |
| 44 | + |
| 45 | +@app.route("/login", methods=["POST"]) |
| 46 | +def login(): |
| 47 | + response = jsonify({"msg": "login successful"}) |
| 48 | + access_token = create_access_token(identity="example_user") |
| 49 | + set_access_cookies(response, access_token) |
| 50 | + return response |
| 51 | + |
| 52 | + |
| 53 | +@app.route("/logout", methods=["POST"]) |
| 54 | +def logout(): |
| 55 | + response = jsonify({"msg": "logout successful"}) |
| 56 | + unset_jwt_cookies(response) |
| 57 | + return response |
| 58 | + |
| 59 | + |
| 60 | +@app.route("/protected") |
| 61 | +@jwt_required() |
| 62 | +def protected(): |
| 63 | + return jsonify(foo="bar") |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + app.run() |
0 commit comments