Python
Sign users in from a Python web application using requests and PyJWT, shown with Flask.
This guide signs users in from any Python web application. The onefold part is four plain functions using
requests and PyJWT; the
web wiring is shown with Flask and ports directly to other
frameworks. For Django, see the Django guide.
You need a confidential application with the redirect URI http://localhost:5000/callback. See
Set up an application.
pip install requests "pyjwt[crypto]" flaskThe onefold functions
import base64
import hashlib
import os
import secrets
from urllib.parse import urlencode
import jwt
import requests
ISSUER = "https://onefold.eitozx.com"
CLIENT_ID = os.environ["ONEFOLD_CLIENT_ID"]
CLIENT_SECRET = os.environ["ONEFOLD_CLIENT_SECRET"]
REDIRECT_URI = os.environ["ONEFOLD_REDIRECT_URI"]
jwks_client = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json")
def start_sign_in() -> tuple[str, dict[str, str]]:
"""Return the URL to redirect to, and the values to keep in the user's session."""
verifier = secrets.token_urlsafe(32)
challenge = base64.urlsafe_b64encode(
hashlib.sha256(verifier.encode()).digest()
).rstrip(b"=").decode()
pending = {
"verifier": verifier,
"state": secrets.token_urlsafe(32),
"nonce": secrets.token_urlsafe(32),
}
query = urlencode({
"response_type": "code",
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": "openid identity",
"state": pending["state"],
"nonce": pending["nonce"],
"code_challenge": challenge,
"code_challenge_method": "S256",
})
return f"{ISSUER}/o/authorize/?{query}", pending
def token_request(**params: str) -> dict:
response = requests.post(
f"{ISSUER}/o/token/",
data={**params, "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET},
timeout=10,
)
response.raise_for_status()
return response.json()
def verify_id_token(id_token: str, nonce: str) -> dict:
key = jwks_client.get_signing_key_from_jwt(id_token).key
claims = jwt.decode(
id_token, key, algorithms=["RS256"], audience=CLIENT_ID, issuer=ISSUER
)
if claims.get("nonce") != nonce:
raise ValueError("ID token nonce mismatch")
return claims
def refresh(refresh_token: str) -> dict:
"""Returns new tokens, including a NEW refresh token. The one sent is now spent."""
return token_request(grant_type="refresh_token", refresh_token=refresh_token)Wire it into Flask
import os
from flask import Flask, abort, redirect, request, session
import onefold
app = Flask(__name__)
app.secret_key = os.environ["FLASK_SECRET_KEY"]
@app.get("/login")
def login():
url, pending = onefold.start_sign_in()
session["onefold_pending"] = pending
return redirect(url)
@app.get("/callback")
def callback():
pending = session.pop("onefold_pending", None)
if request.args.get("error"):
return redirect(f"/?error={request.args['error']}")
if not pending or request.args.get("state") != pending["state"]:
abort(400, "Invalid sign-in state")
tokens = onefold.token_request(
grant_type="authorization_code",
code=request.args.get("code", ""),
redirect_uri=onefold.REDIRECT_URI,
code_verifier=pending["verifier"],
)
claims = onefold.verify_id_token(tokens["id_token"], pending["nonce"])
session["user_sub"] = claims["sub"]
session["refresh_token"] = tokens["refresh_token"]
return redirect("/")Flask's default session is a signed cookie: its contents are not encrypted. Keep the refresh
token in server-side storage in production, for example a database row keyed by sub.
Sign out
@app.post("/logout")
def logout():
refresh_token = session.pop("refresh_token", None)
if refresh_token:
requests.post(
f"{onefold.ISSUER}/o/revoke_token/",
data={
"token": refresh_token,
"client_id": onefold.CLIENT_ID,
"client_secret": onefold.CLIENT_SECRET,
},
timeout=10,
)
session.clear()
return redirect("/")This ends the session in your application. The user stays signed in to onefold.
sub is a string. Store it as a string column, not an integer. See
Accounts, applications and grants.