Skip to main content

Python SDK for the Auth Manager API.

Project description

Auth Manager SDK

Python 3.10+ License

A Python SDK for the Auth Manager API providing OAuth2 token management, validation, and offline token handling.

Features

  • Token Management - Access token retrieval and validation
  • Refresh Tokens - Store and manage refresh tokens
  • Offline Tokens - OAuth consent flow for offline access
  • Token Validation - Verify token authenticity and validity

Installation

pip install authmanagersdk

Or using uv:

uv add authmanagersdk

Quick Start

import asyncio
from authmanagersdk import AuthManager

async def main():
    # initialize client
    async with AuthManager(
        base_url="https://api.example.com",
        token="your-bearer-token"  # optional
    ) as client:
        # validate token
        result = await client.validation.verify()
        print(f"Token valid: {result.valid}")

if __name__ == "__main__":
    asyncio.run(main())

API Reference

Client Initialization

from authmanagersdk import AuthManager

# basic initialization
client = AuthManager(base_url="https://api.example.com")

# with authentication token
client = AuthManager(
    base_url="https://api.example.com",
    token="your-bearer-token",
    timeout=30.0  # optional, default: 10.0
)

# use as context manager
async with AuthManager(base_url="...") as client:
    ...

Access Tokens

Retrieve access tokens by ID.

from uuid import UUID

persistent_token_id = UUID("123e4567-e89b-12d3-a456-426614174000")
result = await client.access.retrieve(id=persistent_token_id)

print(f"Access Token: {result.access_token}")
print(f"Expires In: {result.expires_in} seconds")

Response Model: AccessTokenResult

  • access_token: str - The access token string
  • expires_in: int - Token expiration time in seconds

Offline Tokens

Handle OAuth consent flow for offline access tokens.

Initiate Consent

# get consent url
consent = await client.offline.request_consent(
    client_id="your-client-id",
    user_id="user-123"
)

print(f"Redirect user to: {consent.consent_url}")

Handle Callback

# after user consents and is redirected back
result = await client.offline.callback(
    code="auth-code-from-redirect",
    state="state-from-initiate"
)

print(f"Persistent Token ID: {result.persistent_token_id}")

Handle Callback Errors

# if user denies consent
result = await client.offline.callback(
    code="",
    state="state-from-initiate",
    error="access_denied",
    error_description="User denied consent"
)

Revoke Offline Token

from uuid import UUID

persistent_token_id = UUID("123e4567-e89b-12d3-a456-426614174000")
result = await client.offline.revoke(id=persistent_token_id)

print(f"Revoked: {result.revoked}")

Models:

  • OfflineConsentResult - Consent initiation response
  • OfflineTokenResult - Offline token callback response
  • OfflineTokenRevocationResult - Revocation response

Refresh Tokens

Store refresh tokens for later use.

# store refresh token
result = await client.refresh.store(
    refresh_token="your-refresh-token-string"
)

print(f"Stored with ID: {result.id}")

Response Model: RefreshTokenIdResult

  • id: UUID - The stored refresh token ID

Token Validation

Verify token authenticity and validity.

# requires authenticated client
async with AuthManager(
    base_url="https://api.example.com",
    token="token-to-validate"
) as client:
    result = await client.validation.verify()
    print(f"Valid: {result.valid}")

Response Model: TokenValidationResult

  • valid: bool - Whether token is valid

Authentication

The SDK supports Bearer token authentication:

# set token during initialization
client = AuthManager(
    base_url="https://api.example.com",
    token="your-bearer-token"
)

# or set/update token later
client.set_token("new-bearer-token")

Configuration

Environment Variables

You can configure the API URL via environment variable:

export AUTH_MANAGER_API_URL=https://api.example.com

Then in your code:

import os
from authmanagersdk import AuthManager

api_url = os.getenv("AUTH_MANAGER_API_URL", "http://localhost:8000")
client = AuthManager(base_url=api_url)

Timeouts

Configure request timeout:

client = AuthManager(
    base_url="https://api.example.com",
    timeout=30.0
)

Error Handling

The SDK raises specific exceptions for different error scenarios:

from authmanagersdk.schemas.exceptions import (
    AuthManagerApiError,
    AuthManagerConnectionError
)

try:
    async with AuthManager(base_url="...") as client:
        result = await client.validation.verify()
except AuthManagerConnectionError as e:
    print(f"Connection failed: {e}")
except AuthManagerApiError as e:
    print(f"API error: {e}")
    print(f"Status code: {e.status_code}")
    print(f"Response: {e.response}")

Exception Types:

  • AuthManagerConnectionError - Network/connection issues
  • AuthManagerApiError - API errors (4xx, 5xx responses)

Type Safety

All models are auto-generated from the OpenAPI spec:

from authmanagersdk.schemas.models import (
    AccessTokenResult,
    OfflineTokenResult,
    RefreshTokenIdResult,
    TokenValidationResult,
)

Development

This project uses uv for dependency management.

Setup

# Install dependencies
uv sync

# Run tests
uv run pytest

# Run linter
uv run ruff check

# Format code
uv run ruff format

# Type checking
uv run ty check

Generate Models

Models are auto-generated from the backend OpenAPI spec:

# start the backend first
cd ../auth-manager && make dev-local

# generate models (in another terminal)
cd sdk && make generate

Running Tests

# All tests
make test

Versioning

Version Format

Tags MUST start with sdk/ prefix to be recognized:

  • sdk/0.1.0 → version 0.1.0
  • sdk/1.2.3 → version 1.2.3
  • sdk/2.0.0-beta.1 → version 2.0.0b1

Note: Tags without sdk/ prefix (e.g., v1.0.0) will be ignored by the SDK build process.

Release Process

1. Make Changes

# Make your changes
git add .
git commit -m "Add new feature"

2. Create Version Tag

# For new release
git tag sdk/0.2.0

# Push tag
git push origin sdk/0.2.0

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

Copyright (c) 2025 Open Brain Institute

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

authmanagersdk-1.0.0.tar.gz (14.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

authmanagersdk-1.0.0-py3-none-any.whl (10.8 kB view details)

Uploaded Python 3

File details

Details for the file authmanagersdk-1.0.0.tar.gz.

File metadata

  • Download URL: authmanagersdk-1.0.0.tar.gz
  • Upload date:
  • Size: 14.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for authmanagersdk-1.0.0.tar.gz
Algorithm Hash digest
SHA256 70a1c67ddb4888d14d4659d2678e99f6014c0dfff6f67e91b855a3433307bfd0
MD5 cd849bf14ac0fe329ad665bf429958d0
BLAKE2b-256 987c8328778ac977d2de177110a91ebe76f42103a57dc98c4386d4fc9489c795

See more details on using hashes here.

Provenance

The following attestation bundles were made for authmanagersdk-1.0.0.tar.gz:

Publisher: sdk-publish.yml on openbraininstitute/auth-manager

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file authmanagersdk-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: authmanagersdk-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 10.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for authmanagersdk-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f8f4dabd16267ee2d09b14c7b1240485ddb3b2d5bba3614ba66de445cc726b67
MD5 f463d953e0ccf764a40e17e608197b6b
BLAKE2b-256 e30d844c430c839344a59667d5838916b4460d9760e6c3da6c911ffd89d17313

See more details on using hashes here.

Provenance

The following attestation bundles were made for authmanagersdk-1.0.0-py3-none-any.whl:

Publisher: sdk-publish.yml on openbraininstitute/auth-manager

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page