Server-backed flow
Register an exact HTTPS callback. On the backend, generate a new random state and PKCE verifier, derive its S256 challenge, and store the transaction in a short-lived server session tied to the browser. Redirect to https://auth.bhauu.online/oauth/authorize with response_type=code and scope=profile email. At callback, validate state and exchange the code once. Include a server-held client secret only if this registered client uses one; the programming language alone does not make it confidential.
import base64, hashlib, secrets
from urllib.parse import urlencode
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
app = FastAPI()
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b'=').decode('ascii')
@app.get('/auth/bhauu/start')
async def start(request: Request):
verifier, state = b64url(secrets.token_bytes(32)), b64url(secrets.token_bytes(32))
challenge = b64url(hashlib.sha256(verifier.encode('ascii')).digest())
# Persist {state, verifier} in a short-lived server transaction tied to this browser.
query = urlencode({'client_id': 'YOUR_CLIENT_ID', 'redirect_uri': 'https://example.com/auth/callback', 'response_type': 'code', 'scope': 'profile email', 'state': state, 'code_challenge': challenge, 'code_challenge_method': 'S256'})
return RedirectResponse('https://auth.bhauu.online/oauth/authorize?' + query)
@app.get('/auth/callback')
async def callback(request: Request, code: str, state: str):
# Load and consume the saved transaction. Reject if state mismatches.
pending = None # Replace with your server transaction lookup.
if not pending or not secrets.compare_digest(state, pending['state']):
raise HTTPException(400, 'Invalid callback')
# Exchange code server-side using pending['verifier'] (see Python guide).
raise HTTPException(501, 'Complete the server transaction and exchange before enabling')Token exchange
Once the server transaction is implemented, use the Python token request with the validated code and original verifier. The intentionally incomplete handler above rejects rather than claiming a login succeeded.
Complete application sign-in
Use the returned access token with https://auth.bhauu.online/oauth/userinfo if scoped identity claims are needed. Establish an HttpOnly, Secure, SameSite application-session cookie where suitable, with CSRF protection. Clear the pending state and do not expose tokens to templates or logs. Handle local logout and Bhauu-side revocation separately.