Skip to main content

Machine-to-machine AWS Cognito OAuth2 client credentials and access token validation.

Project description

m2m-cognito

m2m-cognito is a small Python library for machine-to-machine flows against Amazon Cognito: on the caller side it performs OAuth2 client credentials requests to Cognito’s token endpoint and returns a structured token response; on the API/resource-server side it validates Cognito-issued JWT access tokens with the pool’s JWKS, optional client allowlists, and configurable scope checks. The public surface is two main types—CognitoM2MClient and CognitoAccessTokenValidator—plus result dataclasses and exceptions.

Requirements

  • Python: 3.10 or newer (requires-python >=3.10).
  • Dependencies: pyjwt[crypto]>=2.12.1, requests>=2.33.1.

Installation

From PyPI:

pip install m2m-cognito
uv add m2m-cognito

From a local checkout of this repository (editable install):

pip install -e .
uv add --editable .

The import package name is m2m_cognito (underscore); the distribution name on PyPI is m2m-cognito (hyphen).

Usage

Obtain an access token (client credentials)

Configure CognitoM2MClient with your Cognito app client’s token URL, client ID, and client secret. Call fetch_token with one or more OAuth2 scopes (string or sequence). On success you get a TokenResponse with access_token, optional expires_in and token_type, and raw (the full parsed JSON for forward compatibility).

from m2m_cognito import CognitoM2MClient

client = CognitoM2MClient(
    token_url="https://your-auth-domain.example.com/oauth2/token",
    client_id="7a8b9c0d1e2f3g4h5i6j7k8",
    client_secret="your-client-secret",
)
response = client.fetch_token(scopes=["api.example.com/read", "api.example.com/write"])
bearer = response.access_token

Validate an access token (API side)

Build a CognitoAccessTokenValidator from the user pool’s AWS region and user pool ID. Optionally restrict allowed client IDs, require scopes with scope_match of "all" (every required scope present) or "any" (at least one overlap), and set audience if your tokens include aud and you want it verified. Pass the raw JWT string (no Bearer prefix) to validate. On success you get ValidatedAccessToken with client_id, scopes (as a frozenset), and full claims.

from m2m_cognito import CognitoAccessTokenValidator

validator = CognitoAccessTokenValidator(
    region="us-west-2",
    user_pool_id="us-west-2_AbCdEfGhI",
    allowed_client_ids={"7a8b9c0d1e2f3g4h5i6j7k8", "another-app-client-id"},
    required_scopes={"api.example.com/read"},
    scope_match="all",
    audience=None,  # omit or set to verify JWT aud
)
validated = validator.validate(jwt_string_from_authorization_header)
subject_client = validated.client_id

Process Flow

Overview

At the top level, AWS Cognito has a user pool. Within that user pool, are resource servers, corresponding to API servers, and Application clients, which are the systems that will connect to the APIs.

Setup

To begin to use Cognito for API authentication and authorization you must first create the required resources:

  • User pool
    • Resource server within the user pool. The resource server will have:
      • A human name (My API)
      • An identifier (my_api)
      • Custom scopes (or permissions - read, write) these scopes are referred to by joining the resource server identifier with the scope name, ie. my_api/read
    • Application client. These clients will have:
      • A client ID
      • A client secret
      • Allowed scopes

Flow

To connect to a resource server or API, a client will first connect to Cognito using its client id and client secret and obtain a temporary token. By default, this token will last for 1 hour.

This token will be sent as an authentication Bearer token to the server. That server will then validate that token with Cognito. If valid, the response will include the client id, and the valid scopes for the session. The server will then provide the corresponding data to the client.

Error handling

All library-specific errors subclass M2MCognitoError. Typical cases:

Exception When it usually occurs
M2MCognitoError Base type; catch this if you want a single handler for any library error.
CognitoTokenRequestError Token HTTP request failed, non-success status, invalid JSON, missing access_token, OAuth2 error / error_description in the body, or empty scopes passed to fetch_token. Optional attributes: status_code, error_code, error_description, response_body (useful for logging—avoid echoing secrets).
TokenValidationError JWT cannot be verified (signature, issuer, expiry, required claims), wrong token_use, missing client_id, client_id not in allowed_client_ids, or malformed scope claim. Also the base class for scope failures below.
InsufficientScopeError Cryptographically valid token, but required_scopes is non-empty and the token’s scopes do not satisfy scope_match (all vs any). Exposes token_scopes and required_scopes for messaging or metrics.

Prefer catching the specific types where you branch on behavior; use M2MCognitoError only for broad “Cognito/M2M layer failed” handling.

Configuration hints

  • Token URL: If you use a Cognito hosted UI domain (custom or Amazon-provided), the client-credentials token endpoint is typically https://<your-domain>/oauth2/token (same host as the hosted UI, path /oauth2/token). See Using the resource server with the hosted UI and OAuth 2.0 and related Cognito OAuth2 documentation.
  • Issuer and JWKS: For a user pool in region with id user_pool_id, Cognito’s issuer is https://cognito-idp.<region>.amazonaws.com/<user_pool_id> and the JWKS URL is <issuer>/.well-known/jwks.json. CognitoAccessTokenValidator builds these automatically from region and user_pool_id.

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

m2m_cognito-0.1.5.tar.gz (36.4 kB view details)

Uploaded Source

Built Distribution

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

m2m_cognito-0.1.5-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file m2m_cognito-0.1.5.tar.gz.

File metadata

  • Download URL: m2m_cognito-0.1.5.tar.gz
  • Upload date:
  • Size: 36.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.5

File hashes

Hashes for m2m_cognito-0.1.5.tar.gz
Algorithm Hash digest
SHA256 6c33acdd81dbf95327b66f79e7e2595b1a713725c2c4b8a6db53c36414ba1ab0
MD5 0f6a87680cfbbde11c9a0572ce315284
BLAKE2b-256 526b8b0d78f9c30c8c67f2d17bacf3f1d0cba004db07bbf879fa7fb93b4bb6e7

See more details on using hashes here.

File details

Details for the file m2m_cognito-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: m2m_cognito-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 10.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.5

File hashes

Hashes for m2m_cognito-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 440f12e66d68432b8c47c082870eea0da6ef4253022e813c124ca34ee1382e70
MD5 f9123b7e578db1575bcd95c1795df6bf
BLAKE2b-256 1c239da7b0907e8bc7119a64befb4e71b784ee73809a9dd836483478b2c46e60

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