Created
September 19, 2022 10:25
-
-
Save TheOnlyWayUp/950402b17b88797f527e3935f31f913a to your computer and use it in GitHub Desktop.
Personal Cookie Handler script with Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""An example script to display how the Cookie Handler can be used to securely store any python dictionary. | |
I made the Cookie Handler Script to help with managing state during multi-provider oauth (First Microsoft Teams, then Discord). Maintaining state during OAuth is good practice, and can prevent serious security vulnerabilities. | |
In this example, we have two routes, "/add_cookie" and "/show_cookie", with the former redirecting to the latter. When a user visits the add cookie route, a random dictionary is generated with their IP Address and a uuid4(), which is securely stored by the cookie_handler, a uuid is returned which can be set as the cookie's value. The user is then redirected to the show cookie route, where the cookie is fetched and displayed to the user. | |
""" | |
from fastapi import FastAPI, Request, Cookie | |
from fastapi.responses import RedirectResponse | |
from cookie_handler import CookieHandler | |
from uuid import uuid4 | |
ch = CookieHandler() | |
@app.get("/add_cookie") | |
async def add_cookie(request: Request): | |
resp = RedirectResponse("/show_cookie") | |
cookie_key = await ch.create_cookie(data={"ip_address": request.client.host, "password": str(uuid4)}, ttl=30) | |
# You can securely store any data here, the key expires after 30 seconds. I personally use the cookie_handler to store state during oauth, especially when the user has to undergo multiple steps, it adds vulnerability to your flow, which can be alleviated by maintaining state. | |
resp.set_cookie(key="session", value=cookie_key) | |
return resp | |
@app.get("/show_cookie") | |
async def show_cookie(request: Request, session: str = Cookie(default=None)): | |
return ch.retrieve_cookie(session) | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="127.0.0.1", port=8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment