This guide will help you get up and running with FastAPIOAuthRBAC in your FastAPI project.
- Python 3.9+
- A running database (SQLite, PostgreSQL, MySQL) supported by SQLAlchemy.
- A FastAPI application.
You can install the library directly from your preferred package manager:
# Basic installation (no DB driver)
pip install fastapi-oauth-rbac
# With SQLite support
pip install "fastapi-oauth-rbac[sqlite]"
# With PostgreSQL support
pip install "fastapi-oauth-rbac[postgres]"
# Using uv
uv add fastapi-oauth-rbac --extra sqliteGetting started is as simple as initializing the FastAPIOAuthRBAC class. By default, it uses environment variables (prefixed with FORBAC_) for configuration. You can also pass a custom Settings object for more control.
from fastapi import FastAPI
from fastapi_oauth_rbac import FastAPIOAuthRBAC, Settings
app = FastAPI()
# Initialize with default settings (loads from .env)
auth = FastAPIOAuthRBAC(app)
# OR pass explicit settings
# custom_settings = Settings(DATABASE_URL="...", ...)
# auth = FastAPIOAuthRBAC(app, settings=custom_settings)
# Add the essential authentication routes (login, logout, signup, /me)
auth.include_auth_router()
# Add the Admin Dashboard (Explicitly required)
auth.include_dashboard()You can provide your own SQLAlchemy model (e.g., to add extra fields like phone_number or avatar). Your model should ideally inherit from UserBaseMixin or at least include its fields.
from fastapi_oauth_rbac import UserBaseMixin, Base
class MyUser(Base, UserBaseMixin):
__tablename__ = "my_custom_users"
phone: str = Column(String)
# Pass it during initialization
auth = FastAPIOAuthRBAC(app, user_model=MyUser)Use the requires_permission dependency to enforce RBAC on your endpoints.
from fastapi import Depends
from fastapi_oauth_rbac import requires_permission
@app.get("/admin-data", dependencies=[Depends(requires_permission("users:manage"))])
async def get_sensitive_data():
return {"message": "Only those with 'users:manage' permission can see this!"}- Go to Configuration to learn about environment variables.
- Learn about the NIST RBAC Model used by this library.
- Explore the API Reference for more advanced usage.