implementing-saaskit-python

Implements Scalekit SaaSKit authentication in Python web frameworks (Django, FastAPI, or Flask) using scalekit-sdk-python. Use when adding auth to a Django, FastAPI, or Flask project, or when the user mentions Python web authentication with Scalekit.

scalekit-inc/authstack18 installsMITSynced Aug 26

Works with

Claude CodeCursorCodex CLIGitHub CopilotGemini CLI
---
name: implementing-saaskit-python
description: Implements Scalekit SaaSKit authentication in Python web frameworks (Django, FastAPI, or Flask) using scalekit-sdk-python. Use when adding auth to a Django, FastAPI, or Flask project, or when the user mentions Python web authentication with Scalekit.
license: MIT
---

# SaaSKit Auth — Python

Implements Scalekit authentication in Django, FastAPI, or Flask using `scalekit-sdk-python`.

## Guardrails

- **MUST** read `SCALEKIT_ENVIRONMENT_URL`, `SCALEKIT_CLIENT_ID`, and `SCALEKIT_CLIENT_SECRET` from environment variables; **MUST NOT** hardcode credentials.
- **MUST** compare the `oauth_state` cookie against the callback's `state` parameter before calling `authenticate_with_code`, and reject on mismatch (CSRF check).
- **MUST** set the `oauth_state` cookie with `httponly`, `secure`, and `samesite="lax"`.
- **MUST NOT** treat a successful callback as authenticated without completing `authenticate_with_code` and storing the result in the session — clear session/cookies on logout.

## Framework detection

Before generating code, detect which framework is in use:

1. Check for `django` in `requirements.txt` / `pyproject.toml` → Django
2. Check for `fastapi` → FastAPI
3. Check for `flask` → Flask
4. If unclear, ask the user.

## Quick setup

```bash
pip install scalekit-sdk-python python-dotenv
```

```python
import os
from dotenv import load_dotenv
from scalekit import ScalekitClient

load_dotenv()

sc = ScalekitClient(
    env_url=os.getenv("SCALEKIT_ENVIRONMENT_URL"),
    client_id=os.getenv("SCALEKIT_CLIENT_ID"),
    client_secret=os.getenv("SCALEKIT_CLIENT_SECRET"),
)
```

## Framework routing

Each framework has different patterns for routes, middleware, and session storage. Companion files live **next to this `SKILL.md`** in the skill package — open them with the file tool when implementing that framework:

| Framework | Auth middleware | Session store | Reference |
|---|---|---|---|
| Django | Custom middleware class | Django sessions (DB/cache) | [django-reference.md](django-reference.md) (bundled) |
| FastAPI | Dependency injection | Server-side or JWT | **This file** — "Default workflow (FastAPI example)" below |
| Flask | `@login_required` decorator | Flask-Session | [flask-reference.md](flask-reference.md) (bundled) |

## Default workflow (FastAPI example)

```python
import os, secrets
from fastapi import FastAPI, Request, Response
from fastapi.responses import RedirectResponse
from dotenv import load_dotenv
from scalekit import ScalekitClient

load_dotenv()

app = FastAPI()
REDIRECT_URI = os.getenv("SCALEKIT_REDIRECT_URI", "http://localhost:8000/auth/callback")

sc = ScalekitClient(
    env_url=os.getenv("SCALEKIT_ENVIRONMENT_URL"),
    client_id=os.getenv("SCALEKIT_CLIENT_ID"),
    client_secret=os.getenv("SCALEKIT_CLIENT_SECRET"),
)

@app.get("/auth/login")
def login(response: Response):
    state = secrets.token_urlsafe(32)
    from scalekit.common.scalekit import AuthorizationUrlOptions
    options = AuthorizationUrlOptions()
    options.state = state
    response = RedirectResponse(sc.get_authorization_url(REDIRECT_URI, options))
    response.set_cookie("oauth_state", state, httponly=True, samesite="lax", secure=True)
    return response

@app.get("/auth/callback")
def callback(request: Request, code: str, state: str):
    stored = request.cookies.get("oauth_state")
    if not stored or stored != state:
        return Response("CSRF mismatch", status_code=403)
    result = sc.authenticate_with_code(code, REDIRECT_URI)
    # Store result.user and tokens in your session mechanism
    response = RedirectResponse("/dashboard")
    response.delete_cookie("oauth_state")
    return response

@app.get("/auth/logout")
def logout(request: Request):
    from scalekit.common.scalekit import LogoutUrlOptions
    logout_url = sc.get_logout_url(options=LogoutUrlOptions(post_logout_redirect_uri="http://localhost:8000"))
    # Clear your session here
    return RedirectResponse(logout_url)
```

If `authenticate_with_code` raises an exception, verify the redirect URI matches the dashboard exactly.

For Django and Flask patterns, see the framework-specific references linked in the table above.

## Deep reference

- Auth flows: [docs.scalekit.com/authenticate/fsa/quickstart](https://docs.scalekit.com/authenticate/fsa/quickstart/)
- Sessions: [docs.scalekit.com/authenticate/fsa/sessions](https://docs.scalekit.com/authenticate/fsa/sessions/)

## When to switch skills

- Use `implementing-saaskit` for the general (non-Python-specific) integration guide.
- Use `managing-saaskit-sessions` for advanced session handling.
- Use `implementing-access-control` for RBAC after auth is working.

More Security skills

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

318.9k

azure-messaging

microsoft/azure-skills

Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing issues, and SDK configuration problems. WHEN: event hub SDK error, service bus SDK issue, messaging connection failure, AMQP error, event processor host issue, message lock lost, message lock expired, lock renewal, lock renewal batch, send timeout, receiver disconnected, SDK troubleshooting, azure messaging SDK, event hub consumer, service bus queue issue, topic subscription error, enable logging event hub, service bus logging, eventhub python, servicebus java, eventhub javascript, servicebus dotnet, event hub checkpoint, event hub not receiving messages, service bus dead letter, batch processing lock, session lock expired, idle timeout, connection inactive, link detach, slow reconnect, session error, duplicate events, offset reset, receive batch.

310.3k

azure-compliance

microsoft/azure-skills

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

293.2k

← All Security skills

Check your AI visibility

One URL in, a 0–100 score and the exact fixes out.

RUN THE CHECK

Browse all the tools

15 tools across six categories
13 of them never send your data anywhere

Free · No signup · No trial clock

SEE THE DIRECTORY