Quick Start

Get a working AllSafe Fast authentication system running in under five minutes. This guide walks you through installation, configuration, and protecting your first route with email/password authentication.

Prerequisites

  • Python 3.11 or later
  • FastAPI project (or create a new one)
  • For production: PostgreSQL and Redis (not needed for this quick start)

Step 1: Install AllSafe Fast

Install AllSafe Fast using pip:

terminal
pip install allsafe-fast

Or with Poetry:

terminal
poetry add allsafe-fast

Step 2: Configure AllSafe Fast

AllSafe Fast can be configured via environment variables or directly through the AuthConfig class. For this quick start, we'll use the in-memory storage adapter (no database required):

terminal
# Set the secret key (required) export ALLSAFE_SECRET_KEY="dev-secret-key-change-in-production" # Use development environment (in-memory storage) export ALLSAFE_ENV="development" # No database URL needed for development — in-memory adapter is used
ℹ In-Memory Storage

In development mode, AllSafe Fast uses an in-memory storage adapter. This means all data (users, sessions, etc.) is stored in process memory and lost on restart. This is perfect for development and testing. For production, you'll configure a PostgreSQL database — see the Database Architecture page.

Step 3: Create the Auth Instance

Create an Auth instance and attach it to your FastAPI application. The Auth class is the main entry point for AllSafe Fast:

from fastapi import FastAPI, Depends
from allsafe_fast import Auth, AuthConfig, UserPrincipal

# Create the FastAPI app
app = FastAPI(title="My App")

# Create the Auth instance
# AuthConfig reads from environment variables by default
# You can also pass overrides directly:
auth = Auth(AuthConfig(
    secret_key="dev-secret-key-change-in-production",
    env="development",
))

# Attach the auth router to your app
# This adds sign-in, sign-up, refresh, and other auth endpoints
app.include_router(auth.router)

Step 4: Protect Your First Route

Use the auth.user() dependency to protect routes. This ensures only authenticated users can access them:

# Public route — no authentication required
@app.get("/")
async def root():
    return {"message": "Welcome to My App"}

# Protected route — any authenticated user can access
@app.get("/api/me")
async def get_me(user: UserPrincipal = Depends(auth.user())):
    return {
        "id": str(user.id),
        "email": user.email,
        "email_verified": user.email_verified,
        "roles": list(user.roles),
        "permissions": list(user.permissions),
    }

# Admin-only route — requires the "admin" role
@app.get("/api/admin")
async def admin_only(user: UserPrincipal = Depends(auth.user(role="admin"))):
    return {"message": "Hello, admin!"}

# Permission-protected route — requires specific permission
@app.post("/api/reports/export")
async def export_report(
    user: UserPrincipal = Depends(auth.user(permission="reports:export"))
):
    return {"message": "Report exported"}

Complete Working Example

Here is the complete, runnable application. Save it as main.py:

# main.py
from fastapi import FastAPI, Depends
from allsafe_fast import Auth, AuthConfig, UserPrincipal

app = FastAPI(title="My App with AllSafe Fast")

# Create Auth instance with development configuration
auth = Auth(AuthConfig(
    secret_key="dev-secret-key-change-in-production",
    env="development",
))

# Include the auth router (adds /auth/* endpoints)
app.include_router(auth.router)

# --- Public Routes ---

@app.get("/")
async def root():
    return {"message": "Welcome! Visit /docs for API documentation."}

# --- Protected Routes ---

@app.get("/api/me")
async def get_me(user: UserPrincipal = Depends(auth.user())):
    return {
        "id": str(user.id),
        "email": user.email,
        "email_verified": user.email_verified,
        "roles": list(user.roles),
        "permissions": list(user.permissions),
    }

@app.get("/api/admin")
async def admin_panel(user: UserPrincipal = Depends(auth.user(role="admin"))):
    return {"message": "Welcome to the admin panel", "admin": user.email}

# --- Run the app ---
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Step 5: Run the Application

Start the development server:

terminal
# Run the application python main.py # Or using uvicorn directly uvicorn main:app --reload --port 8000 # You should see: # INFO: Uvicorn running on http://0.0.0.0:8000 # INFO: Application startup complete.

Step 6: Test with curl

Test the authentication flow using curl. AllSafe Fast automatically provides sign-up and sign-in endpoints:

Sign Up a New User

terminal
# Sign up a new user curl -X POST http://localhost:8000/auth/sign-up \ -H "Content-Type: application/json" \ -d '{"email": "alice@example.com", "password": "secure-password123"}' # Response: # { # "user": {"id": "...", "email": "alice@example.com", ...}, # "access_token": "eyJ...", # "refresh_token": "eyJ..." # }

Access a Protected Route

terminal
# Access the protected /api/me endpoint with the access token curl http://localhost:8000/api/me \ -H "Authorization: Bearer eyJ..." # Response: # { # "id": "550e8400-e29b-41d4-a716-446655440000", # "email": "alice@example.com", # "email_verified": false, # "roles": [], # "permissions": [] # }

Try the Admin Route (Without Admin Role)

terminal
# Try to access the admin route without the admin role curl http://localhost:8000/api/admin \ -H "Authorization: Bearer eyJ..." # Response (403 Forbidden): # { # "detail": "User does not have required role: admin" # }

Sign In and Refresh

terminal
# Sign in with the created user curl -X POST http://localhost:8000/auth/sign-in \ -H "Content-Type: application/json" \ -d '{"email": "alice@example.com", "password": "secure-password123"}' # Refresh the access token using the refresh token curl -X POST http://localhost:8000/auth/refresh \ -H "Content-Type: application/json" \ -d '{"refresh_token": "eyJ..."}'

What's Next

Congratulations! You have a working authentication system. Here's where to go from here:

TopicLinkWhat You'll Learn
ConfigurationSecurity ArchitectureAll configuration options, environment variables, and security settings
AuthorizationAuthorization OverviewRoles, permissions, and protecting routes with fine-grained access control
DatabaseDatabase ArchitectureSetting up PostgreSQL for production, migrations, and schema design
ProductionProduction ChecklistEverything you need before deploying to production
💡 Interactive API Docs

FastAPI automatically generates interactive API documentation. Visit http://localhost:8000/docs for Swagger UI or http://localhost:8000/redoc for ReDoc. You can use these to test all auth endpoints directly from your browser.

⚠ Before Going to Production

This quick start uses the in-memory storage adapter and a development secret key. Before deploying to production, you must: (1) set a strong, unique secret key, (2) configure a PostgreSQL database, (3) configure Redis for rate limiting, and (4) complete the Production Checklist.

Environment Variables Reference

AllSafe Fast reads configuration from environment variables. Here are the key ones for this quick start:

ALLSAFE_SECRET_KEY
Secret key for JWT signing. Required. Default: "change-me-please-..." (rejected in production).
ALLSAFE_ENV
Environment name. Options: development, production, staging, test. Default: development.
ALLSAFE_DATABASE_URL
PostgreSQL connection URL. If not set, in-memory storage is used. Format: postgresql+asyncpg://...
ALLSAFE_REDIS_URL
Redis connection URL for rate limiting. If not set, in-memory rate limiter is used.
ALLSAFE_ACCESS_TOKEN_EXPIRE
Access token lifetime in seconds. Default: 900 (15 minutes).
ALLSAFE_REFRESH_TOKEN_EXPIRE
Refresh token lifetime in seconds. Default: 2592000 (30 days).
ALLSAFE_RATE_LIMIT
Max requests per window. Default: 5.
ALLSAFE_RATE_LIMIT_WINDOW
Rate limit window in seconds. Default: 900 (15 minutes).