Skip to main content

Simple Python library for Azure B2C OAuth2 refresh token authentication

Project description

B2C OAuth Client

Simple, focused Python library for Azure B2C OAuth2 refresh token authentication.

Python 3.10+ License: MIT

Disclaimer

B2C OAuth Client is an independent, open-source Python library for Azure B2C OAuth2 refresh token authentication. This library is:

  • Not affiliated with Microsoft Corporation - This is a third-party library, not an official Microsoft product
  • Not endorsed by Microsoft - Microsoft does not endorse or support this library
  • Not connected to any specific Azure B2C tenant - The library is generic and works with any Azure B2C tenant
  • Use at your own risk - Users are responsible for their use of this library

Legal Considerations

When using this library with any Azure B2C tenant, you must:

  • Comply with the Azure B2C tenant's terms of service
  • Comply with Microsoft's terms of service for Azure services
  • Respect any API rate limits or usage restrictions
  • Not use the library for unauthorized access or malicious purposes

This library implements standard OAuth2 refresh token flow as documented by Microsoft. It does not reverse engineer proprietary protocols, bypass security measures, or violate any intellectual property rights. The implementation follows publicly available OAuth2 and Azure B2C documentation.

Privacy and Security

  • No data collection - This library does not collect or transmit any user data
  • No secrets stored - All authentication credentials must be provided by the user
  • No tracking - The library does not include any tracking or analytics

Features

  • ✅ Simple refresh token flow for Azure B2C
  • ✅ Automatic token expiration handling
  • ✅ Clean, minimal API
  • ✅ No external dependencies beyond requests
  • ✅ Fully typed with type hints
  • ✅ Works with any Azure B2C tenant

Installation

pip install b2c-oauth-client

Quick Start

from b2c_oauth_client import B2COAuthClient, AuthenticationError

# Initialize client with your Azure B2C configuration
client = B2COAuthClient(
    tenant="your-tenant.onmicrosoft.com",
    client_id="your-client-id",
    policy="B2C_1_YourPolicy",
    scope="https://your-tenant.onmicrosoft.com/your-api/your.scope openid profile offline_access"
)

# Refresh token to get new access token
try:
    token = client.refresh_token("your_refresh_token")

    # Use the access token
    print(f"Access token: {token.access_token[:50]}...")
    print(f"Expires at: {token.expires_at}")

    # Save the new refresh token for future use
    if token.refresh_token:
        print(f"New refresh token: {token.refresh_token[:50]}...")
        # Save token.refresh_token to your storage

except AuthenticationError as e:
    print(f"Authentication failed: {e}")

API Reference

B2COAuthClient

Main client class for Azure B2C authentication.

Constructor

B2COAuthClient(
    tenant: str,
    client_id: str,
    policy: str,
    scope: str,
    base_url: str | None = None
)

Parameters:

  • tenant: Azure B2C tenant name (e.g., "your-tenant.onmicrosoft.com")
  • client_id: Application (client) ID from Azure B2C
  • policy: B2C policy name (e.g., "B2C_1_YourPolicy")
  • scope: Space-separated list of scopes to request
  • base_url: Optional base URL for B2C login (defaults to {tenant-name}.b2clogin.com)

Methods

refresh_token(refresh_token: str, session: requests.Session | None = None) -> AuthToken

Refresh an access token using a refresh token.

Parameters:

  • refresh_token: The refresh token to use for authentication
  • session: Optional requests session for connection pooling

Returns: AuthToken object

Raises: AuthenticationError if token refresh fails

is_token_valid(token: AuthToken, buffer_minutes: int = 5) -> bool

Check if a token is still valid (not expired).

Parameters:

  • token: The AuthToken to check
  • buffer_minutes: Consider token invalid if it expires within this many minutes

Returns: True if token is valid, False otherwise

AuthToken

Data class representing an authentication token.

@dataclass(frozen=True)
class AuthToken:
    access_token: str
    refresh_token: str | None
    expires_at: datetime
    token_type: str = "Bearer"

Exceptions

AuthenticationError

Raised when authentication fails (invalid token, network error, etc.)

ConfigurationError

Raised when client configuration is invalid (missing required parameters)

Examples

Basic Usage

from b2c_oauth_client import B2COAuthClient

client = B2COAuthClient(
    tenant="myapp.onmicrosoft.com",
    client_id="12345678-1234-1234-1234-123456789abc",
    policy="B2C_1_SignUpSignIn",
    scope="https://myapp.onmicrosoft.com/api/read openid profile offline_access"
)

token = client.refresh_token("your_refresh_token_here")
print(f"Access token expires at: {token.expires_at}")

Using with Requests Session

import requests
from b2c_oauth_client import B2COAuthClient

session = requests.Session()
client = B2COAuthClient(...)

token = client.refresh_token("your_refresh_token", session=session)

# Use the same session for API calls
headers = {"Authorization": f"{token.token_type} {token.access_token}"}
response = session.get("https://api.example.com/data", headers=headers)

Token Validation

from b2c_oauth_client import B2COAuthClient

client = B2COAuthClient(...)
token = client.refresh_token("your_refresh_token")

# Check if token is still valid
if client.is_token_valid(token):
    print("Token is valid")
else:
    print("Token has expired, need to refresh")

Error Handling

from b2c_oauth_client import B2COAuthClient, AuthenticationError, ConfigurationError

try:
    client = B2COAuthClient(
        tenant="",  # Invalid: empty tenant
        client_id="...",
        policy="...",
        scope="..."
    )
except ConfigurationError as e:
    print(f"Configuration error: {e}")

try:
    token = client.refresh_token("invalid_token")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
    # Handle error (e.g., prompt user to re-authenticate)

Requirements

  • Python 3.10 or higher
  • requests>=2.31.0

Development

Setup

# Clone repository
git clone https://github.com/jvuori/b2c-oauth-client.git
cd b2c-oauth-client

# Install with development dependencies using uv
uv sync --dev

# Run tests
uv run pytest

# Run linting
uv run ruff check src/

# Format code
uv run ruff format src/

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

This library is provided "as-is" without warranty. For issues or questions:

Links

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

b2c_oauth_client-0.0.4.tar.gz (49.5 kB view details)

Uploaded Source

Built Distribution

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

b2c_oauth_client-0.0.4-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file b2c_oauth_client-0.0.4.tar.gz.

File metadata

  • Download URL: b2c_oauth_client-0.0.4.tar.gz
  • Upload date:
  • Size: 49.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for b2c_oauth_client-0.0.4.tar.gz
Algorithm Hash digest
SHA256 9bc98811e9259a223f11ae199bb92b207a665e70664b645b404baf2ac0b72d9d
MD5 b16b51d8de103e1714ed78313d6a4127
BLAKE2b-256 6379141ef7e76cf5586fad8bff7505c1188547fb62fe5304c84951c08e1a67f4

See more details on using hashes here.

File details

Details for the file b2c_oauth_client-0.0.4-py3-none-any.whl.

File metadata

  • Download URL: b2c_oauth_client-0.0.4-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for b2c_oauth_client-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 d159dce8f77cfe68e28681aed5b73a8026a0dd0ed658a5b20056eea985c5abaa
MD5 8b214cf8d7ae738abc70863a737651fc
BLAKE2b-256 97b691a6a5b7dd7418dbd4452b72bd8689fbdd97b261e1a8adc71cb87b0f9d8e

See more details on using hashes here.

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