AWS Cognito JWT authentication library for FastAPI applications
Project description
agr-cognito-py
AWS Cognito JWT authentication library for FastAPI applications, designed for the Alliance of Genome Resources (AGR) ecosystem.
Features
- JWT token validation for AWS Cognito ID and access tokens
- FastAPI dependencies for easy authentication integration
- Support for both user authentication (ID tokens) and machine-to-machine auth (access tokens)
- Admin token generation using OAuth client_credentials flow
- MOD-based permission utilities for AGR applications
- Token caching for improved performance
Installation
pip install agr-cognito-py
Quick Start
Environment Variables
Set the following environment variables:
# Required for token validation
export COGNITO_REGION="us-east-1"
export COGNITO_USER_POOL_ID="us-east-1_xxxxx"
export COGNITO_CLIENT_ID="your-client-id"
# Optional: Additional allowed client IDs (comma-separated)
export COGNITO_ALLOWED_CLIENT_IDS="client1,client2"
# Required for admin token generation
export COGNITO_ADMIN_CLIENT_ID="admin-client-id"
export COGNITO_ADMIN_CLIENT_SECRET="admin-client-secret"
export COGNITO_TOKEN_URL="https://your-domain.auth.region.amazoncognito.com/oauth2/token"
export COGNITO_ADMIN_SCOPE="your-api/scope"
FastAPI Integration
Use Security (recommended) or Depends to protect your endpoints. Security integrates
with Swagger UI's "Authorize" button for easy testing.
from typing import Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Response, Security, status
from sqlalchemy.orm import Session
from agr_cognito_py import get_cognito_user_swagger, get_mod_access, ModAccess
router = APIRouter(prefix="/reference", tags=["Reference"])
@router.post("/", status_code=status.HTTP_201_CREATED)
def create(
request: ReferenceSchemaPost,
user: Dict[str, Any] = Security(get_cognito_user_swagger),
db: Session = Depends(get_db)
):
# user contains: email, name, cognito:groups, cognito:username, token_type
return reference_crud.create(db, request)
@router.delete("/{tag_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_tag(
tag_id: int,
user: Dict[str, Any] = Security(get_cognito_user_swagger),
db: Session = Depends(get_db)
):
# Check MOD-based permissions before deleting
mod_access = get_mod_access(user)
if mod_access == ModAccess.NO_ACCESS:
raise HTTPException(status_code=403, detail="No access")
tag_crud.destroy(db, tag_id, mod_access)
return Response(status_code=status.HTTP_204_NO_CONTENT)
Token Validation
from agr_cognito_py import CognitoAuth, CognitoConfig
# Configure with environment variables
auth = CognitoAuth()
# Or configure explicitly
config = CognitoConfig(
region="us-east-1",
user_pool_id="us-east-1_xxxxx",
client_id="your-client-id"
)
auth = CognitoAuth(config)
# Validate a token
try:
user = auth.validate_token(token)
print(f"User email: {user['email']}")
print(f"User groups: {user['cognito:groups']}")
except JWTError as e:
print(f"Invalid token: {e}")
Admin Token Generation
For machine-to-machine authentication using client credentials:
from agr_cognito_py import get_admin_token, generate_headers, CognitoAdminConfig
import requests
# Get admin token (uses caching automatically)
token = get_admin_token()
# Generate headers for API requests
headers = generate_headers(token)
# Make authenticated request
response = requests.get("https://api.example.com/data", headers=headers)
MOD-based Permissions
For AGR applications requiring Model Organism Database access control:
from agr_cognito_py import get_mod_access, has_mod_access, ModAccess
# Get user's MOD access level
access = get_mod_access(user)
if access == ModAccess.ALL_ACCESS:
print("User has full access")
elif access == ModAccess.WB:
print("User is a WormBase curator")
# Check specific MOD access
if has_mod_access(user, "WB"):
print("User can access WormBase data")
API Reference
Classes
CognitoAuth
Main class for JWT token validation.
CognitoConfig
Configuration for token validation (region, user pool, client ID).
CognitoAdminConfig
Configuration for admin token generation (client credentials flow).
Functions
Token Validation
get_cognito_user_swagger()- FastAPI dependency with Swagger UI integrationget_cognito_user()- FastAPI dependency supporting headers and cookiesrequire_groups(*groups)- FastAPI dependency requiring specific Cognito groups
Admin Tokens
get_admin_token(config, force_refresh)- Get admin access token with cachingget_authentication_token(config)- Alias for get_admin_tokengenerate_headers(token)- Generate Authorization headersclear_token_cache()- Clear the cached admin token
Permissions
get_mod_access(user)- Get ModAccess enum for a userhas_mod_access(user, mod)- Check if user has access to a specific MOD
Enums
ModAccess
NO_ACCESS- No MOD accessALL_ACCESS- Full access to all MODsSGD,RGD,MGI,ZFIN,XB,FB,WB- Specific MOD access
Development
# Clone the repository
git clone https://github.com/alliance-genome/agr_cognito_py.git
cd agr_cognito_py
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linting
ruff check src tests
ruff format src tests
# Type checking
mypy src
License
MIT License - see LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file agr_cognito_py-0.1.0.tar.gz.
File metadata
- Download URL: agr_cognito_py-0.1.0.tar.gz
- Upload date:
- Size: 10.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.8.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9ad30322e0f5558428190152a4b8814bc59fc3c71922b6aca779e101829f514a
|
|
| MD5 |
d532a4fbee265cfc8af230bf0af0c14b
|
|
| BLAKE2b-256 |
7f12eb6de9e10b26f3b587f9acd256d43e5cec6319686b9206b28e119c8889af
|
File details
Details for the file agr_cognito_py-0.1.0-py3-none-any.whl.
File metadata
- Download URL: agr_cognito_py-0.1.0-py3-none-any.whl
- Upload date:
- Size: 12.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.8.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
82474fdea443e717970ba114d512c7fc912220d1a56473ecabe67c37c52b2f40
|
|
| MD5 |
7902871f4913dd8d2b40c2db74e9beed
|
|
| BLAKE2b-256 |
de727957dfaf5e0544793a5218e828db4c5dd7cb5173cbe7719546fb1256675d
|