# Quickstart: Python

The Python SDK, `ohauthcat`, gives you `OhAuthCat`, `sso.get_authorization_url(...)`, `sso.get_profile_and_token(...)` and `RestartSignIn`. Every example on this page is run against the SDK in our test suite.

## Install

The SDK needs Python 3.10 or later.

Install it:

```sh
pip install ohauthcat
```

## Configure

Set server configuration from the dashboard. Keep secrets on the server.

:::tip[Your test keys]
Signed in to the dashboard? [Show your sandbox keys](/get-started/sandbox-keys/) on that page and copy them straight into your environment.
:::

Sandbox and production environments share these hosts: the keys (`sk_test_...` or `sk_live_...`) select the environment, so you never change the host to switch between them.

| Variable                                        | Where it comes from                                                                                                                                                                                              |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OHAUTHCAT_API_KEY`                             | The environment's secret key (`sk_...`), from **API keys**.                                                                                                                                                      |
| `OHAUTHCAT_CLIENT_ID`                           | The environment's publishable key (`pk_...`), from **API keys**. The SDK sends it as the OAuth `client_id`.                                                                                                      |
| `OHAUTHCAT_ENVIRONMENT_ID`                      | The environment ID (`env_...`), shown in the dashboard's quickstart snippet.                                                                                                                                     |
| `OHAUTHCAT_ORGANIZATION`                        | The organization ID (`org_...`) of the customer signing in.                                                                                                                                                      |
| `OHAUTHCAT_REDIRECT_URI`                        | A callback URI registered under **Redirect URIs**.                                                                                                                                                               |
| `OHAUTHCAT_API_ORIGIN`, `OHAUTHCAT_AUTH_ORIGIN` | Leave unset for production: the SDK defaults to `https://api.ohauthcat.com` and `https://auth.ohauthcat.com`. Any other deployment must set both to its own API and auth origins, or sign-in goes to production. |

## Begin and complete a sign-in

The dictionary below is a single-process illustration. Use an expiring shared store with atomic consume and abandoned-attempt cleanup in production. Bind its browser session ID to your application's secure session cookie, never to a user-controlled query parameter.

```python
import hmac
import os
import secrets
import time
from urllib.parse import parse_qs, urlsplit

from ohauthcat import OhAuthCat, RestartSignIn

API_KEY = os.environ.get("OHAUTHCAT_API_KEY")
CLIENT_ID = os.environ.get("OHAUTHCAT_CLIENT_ID")
ENVIRONMENT_ID = os.environ.get("OHAUTHCAT_ENVIRONMENT_ID")
ORGANIZATION = os.environ.get("OHAUTHCAT_ORGANIZATION")
REDIRECT_URI = os.environ.get("OHAUTHCAT_REDIRECT_URI")
if not (API_KEY and CLIENT_ID and ENVIRONMENT_ID and ORGANIZATION and REDIRECT_URI):
    raise RuntimeError("Missing server SSO configuration")

client = OhAuthCat(
    api_key=API_KEY,
    client_id=CLIENT_ID,
    environment_id=ENVIRONMENT_ID,
    timeout_ms=5000,
    max_retries=0,
    # Unset in production; required for any other deployment.
    api_base_url=os.environ.get("OHAUTHCAT_API_ORIGIN"),
    auth_base_url=os.environ.get("OHAUTHCAT_AUTH_ORIGIN"),
)
# Demonstration only: replace with a durable, atomic server-side attempt store.
# Each entry is (browser_session_id, code_verifier, expires_at).
attempts = {}


def begin_sign_in(browser_session_id):
    if not isinstance(browser_session_id, str) or not browser_session_id:
        raise ValueError("Missing initiating browser session")
    state = secrets.token_urlsafe(32)
    authorization = client.sso.get_authorization_url(
        redirect_uri=REDIRECT_URI, state=state, organization=ORGANIZATION
    )
    attempts[state] = (browser_session_id, authorization.code_verifier, time.time() + 300)
    return authorization.url, state


def complete_sign_in(callback_url, browser_session_id):
    callback = urlsplit(callback_url)
    expected = urlsplit(REDIRECT_URI)
    if (callback.scheme, callback.netloc, callback.path) != (
        expected.scheme,
        expected.netloc,
        expected.path,
    ):
        raise ValueError("Unexpected callback location")
    params = parse_qs(callback.query, keep_blank_values=True)
    if any(len(params.get(name, [])) > 1 for name in ("state", "code", "error")):
        raise ValueError("Repeated callback parameter")
    state = params.get("state", [""])[0]
    attempt = attempts.get(state)
    if attempt is None or attempt[2] <= time.time():
        attempts.pop(state, None)
        raise ValueError("Missing or expired sign-in attempt")
    expected_session, code_verifier, _ = attempt
    if not hmac.compare_digest(
        (browser_session_id or "").encode(), expected_session.encode()
    ):
        raise ValueError("Wrong initiating browser session")
    # Consume before the exchange; a failing exchange requires a fresh attempt.
    del attempts[state]
    code = params.get("code", [""])[0]
    if "error" in params or not code:
        raise ValueError("Sign-in failed; start again")
    try:
        result = client.sso.get_profile_and_token(
            code=code, code_verifier=code_verifier, redirect_uri=REDIRECT_URI
        )
    except RestartSignIn:
        raise ValueError("Sign-in interrupted; start a new attempt") from None
    profile = result.profile.model_dump(mode="json")
    if profile["organization_id"] != ORGANIZATION:
        raise ValueError("Unexpected profile organization")
    return profile
```

Your sign-in route calls the begin function and redirects to the returned authorization URL. Your callback route supplies its actual URL and the same trusted browser session ID to the complete function. After a successful organization check, map the returned profile to an allowed local user and create your own secure session. Never log the full profile or token.

Reject wrong state/session, repeated callback parameters, expiry and replay before creating a session. On exchange failure start a new attempt; the code and verifier are single-use. [Token exchange](/sso/how-it-works/) requires both PKCE and the secret key on the auth host.

The example returns a profile, not a provider session. See [identity mapping](/sso/profiles/) and [working with existing auth](/sso/working-with-existing-auth/) for the next step.
