Authentication
Flaxon provides flexible authentication through JWT, sessions, and custom backends.
JWT Authentication
Setup
from flaxon import Flaxon
from flaxon.security import JWTBackend, AuthenticationMiddleware
app = Flaxon("auth-app")
backend = JWTBackend(secret_key="your-secret-key")
app.add_middleware(AuthenticationMiddleware, backend=backend)
Login
from flaxon.security import User
@app.post("/login")
async def login(request):
data = await request.json()
user = await authenticate_user(data["username"], data["password"])
if not user:
raise HTTPException(401, "Invalid credentials")
token = await backend.create_token(user)
return {"token": token, "user": user.to_dict()}
Protecting Routes
from flaxon.security import login_required
@app.get("/profile")
@login_required
async def profile(request):
user = getattr(request, "user")
return {"user": user.to_dict()}
Session Authentication
from flaxon.security import SessionBackend, AuthenticationMiddleware
backend = SessionBackend()
app.add_middleware(AuthenticationMiddleware, backend=backend)
@app.post("/login")
async def login(request):
user = await authenticate_user(data)
session_id = await backend.create_token(user)
response = JSONResponse({"success": True})
response.headers["set-cookie"] = f"session_id={session_id}; HttpOnly; Path=/"
return response
API Key Authentication
from flaxon.security import APIKeyManager, api_key_required
manager = APIKeyManager()
key, hashed = manager.generate_key()
manager.register(key)
app.state.api_key_manager = manager
@app.get("/protected")
@api_key_required
async def protected(request):
return {"data": "secret"}
OAuth2
from flaxon.security import OAuth2Provider, OAuth2Backend
provider = OAuth2Provider(
client_id="your-client-id",
client_secret="your-client-secret",
authorization_endpoint="https://auth.example.com/authorize",
token_endpoint="https://auth.example.com/token",
redirect_uri="https://your-app.com/callback",
)
backend = OAuth2Backend()
backend.register_provider("example", provider)
@app.get("/auth/login")
async def auth_login():
url = backend.get_authorization_url("example")
return RedirectResponse(url)
Password Hashing
from flaxon.security import hash_password, verify_password
# Hash a password
hashed = hash_password("my-password")
# Verify a password
is_valid = verify_password("my-password", hashed)
# Check if rehash is needed
if needs_rehash(hashed):
hashed = hash_password("my-password")
Security Reminder
Always store secret keys in environment variables, not in code. Use FLAXON_SECRET_KEY in production.