Skip to content

webobite-app/keycloak-auth-library

Repository files navigation

Keycloak Auth Library

Python Version License: MIT

A production-ready authentication library for Flask and FastAPI applications using Keycloak with SQLite database synchronization.

# Example usage
from fastapi import FastAPI, Depends
from keycloak_auth.fastapi_integration import get_current_user

app = FastAPI()

@app.get("/protected")
async def protected_route(user: dict = Depends(get_current_user)):
    return {"user_id": user["id"]}

Table of Contents

  1. Features
  2. Installation
  3. Configuration
  4. Usage
  5. Database Schema
  6. Error Handling
  7. Security
  8. Deployment
  9. Troubleshooting

Features

  • ✅ Keycloak JWT authentication
  • ✅ Role-based access control (RBAC)
  • ✅ SQLite/PostgreSQL support
  • ✅ Flask & FastAPI integration
  • ✅ Automatic user synchronization
  • ✅ Token validation with JWKS
  • ✅ Production-ready security
  • ✅ Custom exception hierarchy

Installation

# Using pip
pip install keycloak-auth-library

# Development setup
git clone https://github.com/yourusername/keycloak-auth-library.git
cd keycloak-auth-library
pip install -e .

Configuration

Create .env file:

KEYCLOAK_SERVER_URL=http://localhost:8080
KEYCLOAK_REALM=master
KEYCLOAK_CLIENT_ID=your-client
KEYCLOAK_CLIENT_SECRET=your-secret
DATABASE_URL=sqlite:///auth.db

Usage

Flask Integration

from flask import Flask, g
from keycloak_auth.flask_integration import keycloak_auth

app = Flask(__name__)

@app.route("/protected")
@keycloak_auth(required_roles=["admin"])
def protected_route():
    return {"user": g.user["id"]}

FastAPI Integration

from fastapi import FastAPI, Depends
from keycloak_auth.fastapi_integration import get_current_user

app = FastAPI()

@app.get("/protected")
async def protected_route(user: dict = Depends(get_current_user)):
    return {"user": user["id"]}

Database Schema

CREATE TABLE users (
    id TEXT PRIMARY KEY,
    username TEXT UNIQUE NOT NULL,
    email TEXT UNIQUE NOT NULL
);

CREATE TABLE user_roles (
    user_id TEXT REFERENCES users(id),
    role TEXT NOT NULL
);

Error Handling

try:
    # Authentication code
except AuthenticationError as e:
    # Handle 401 errors
except InsufficientPermissionsError:
    # Handle 403 errors
Code Error Class Description
401 InvalidTokenError Invalid/missing JWT
403 InsufficientPermissions Missing required roles
500 ConfigurationError Invalid setup

Security Best Practices

  1. Use HTTPS in production
  2. Rotate secrets every 90 days
  3. Enable Keycloak brute-force protection
  4. Set token expiration ≤ 1 hour
  5. Use database encryption
  6. Regular security audits

Deployment

# docker-compose.yml
version: '3.8'

services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    environment:
      KEYCLOAK_ADMIN: admin
      KEYCLOAK_ADMIN_PASSWORD: change-me

  app:
    build: .
    environment:
      KEYCLOAK_SERVER_URL: http://keycloak:8080
    depends_on:
      - keycloak

Troubleshooting

Problem: ImportError: cannot import name...
✅ Verify package installation
✅ Check for naming conflicts

Problem: InvalidTokenError
✅ Validate Keycloak configuration
✅ Check token expiration

Problem: Roles not syncing
✅ Verify database permissions
✅ Check Keycloak role mappings

License

MIT License - See LICENSE for details.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published