cezzis-oauth-fastapi 0.0.20__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cezzis_oauth_fastapi/__init__.py +17 -0
- cezzis_oauth_fastapi/__init__.pyi +4 -0
- cezzis_oauth_fastapi/oauth_authorization.py +141 -0
- cezzis_oauth_fastapi/oauth_authorization.pyi +5 -0
- cezzis_oauth_fastapi/oauth_config.py +10 -0
- cezzis_oauth_fastapi/oauth_config.pyi +7 -0
- cezzis_oauth_fastapi-0.0.20.dist-info/METADATA +61 -0
- cezzis_oauth_fastapi-0.0.20.dist-info/RECORD +9 -0
- cezzis_oauth_fastapi-0.0.20.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Cezzis OAuth FastAPI - A lightweight library for OAuth authentication and utilities for fastapi."""
|
|
2
|
+
|
|
3
|
+
from cezzis_oauth_fastapi.oauth_authorization import oauth_authorization
|
|
4
|
+
from cezzis_oauth_fastapi.oauth_config import OAuthConfig
|
|
5
|
+
|
|
6
|
+
# Dynamically read version from package metadata
|
|
7
|
+
try:
|
|
8
|
+
from importlib.metadata import version
|
|
9
|
+
|
|
10
|
+
__version__ = version("cezzis_oauth_fastapi")
|
|
11
|
+
except Exception:
|
|
12
|
+
__version__ = "unknown"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"oauth_authorization",
|
|
16
|
+
"OAuthConfig",
|
|
17
|
+
]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from functools import wraps
|
|
4
|
+
from typing import Callable, Union
|
|
5
|
+
|
|
6
|
+
from cezzis_oauth import (
|
|
7
|
+
OAuth2TokenVerifier,
|
|
8
|
+
TokenVerificationError,
|
|
9
|
+
)
|
|
10
|
+
from fastapi import HTTPException, Request
|
|
11
|
+
|
|
12
|
+
from cezzis_oauth_fastapi.oauth_config import OAuthConfig
|
|
13
|
+
|
|
14
|
+
_logger = logging.getLogger("oauth_authorization")
|
|
15
|
+
|
|
16
|
+
# Cache verifiers by config to avoid recreating them
|
|
17
|
+
_verifiers: dict[tuple, OAuth2TokenVerifier] = {}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _get_config_key(config: OAuthConfig) -> tuple:
|
|
21
|
+
"""Create a hashable key from OAuthConfig for caching verifiers."""
|
|
22
|
+
return (config.domain, config.audience, tuple(config.algorithms), config.issuer)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def oauth_authorization(scopes: list[str], config_provider: Callable[[], OAuthConfig]):
|
|
26
|
+
"""Decorator for OAuth2 authorization with OAuth token verification.
|
|
27
|
+
|
|
28
|
+
Can be applied to:
|
|
29
|
+
- Individual endpoint methods (async functions)
|
|
30
|
+
- APIRouter classes (all methods will be protected)
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
scopes: List of required OAuth scopes.
|
|
34
|
+
config_provider: A callable that returns an OAuthConfig instance.
|
|
35
|
+
|
|
36
|
+
Example:
|
|
37
|
+
# On a method
|
|
38
|
+
@oauth_authorization(scopes=["write:embeddings"], config_provider=get_oauth_config)
|
|
39
|
+
async def get_cocktails(self, _rq: Request):
|
|
40
|
+
...
|
|
41
|
+
|
|
42
|
+
# On a class (protects all methods)
|
|
43
|
+
@oauth_authorization(scopes=["admin:cocktails"], config_provider=get_oauth_config)
|
|
44
|
+
class AdminRouter(APIRouter):
|
|
45
|
+
...
|
|
46
|
+
|
|
47
|
+
# Without scope verification
|
|
48
|
+
@oauth_authorization(scopes=[], config_provider=get_oauth_config)
|
|
49
|
+
async def public_endpoint(self, _rq: Request):
|
|
50
|
+
...
|
|
51
|
+
"""
|
|
52
|
+
required_scopes = scopes or []
|
|
53
|
+
|
|
54
|
+
def decorator(target: Union[Callable, type]) -> Union[Callable, type]:
|
|
55
|
+
# Check if target is a class
|
|
56
|
+
if isinstance(target, type):
|
|
57
|
+
return _wrap_class(target, required_scopes, config_provider())
|
|
58
|
+
else:
|
|
59
|
+
return _wrap_function(target, required_scopes, config_provider())
|
|
60
|
+
|
|
61
|
+
return decorator
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _wrap_function(func: Callable, required_scopes: list[str], oauth_config: OAuthConfig) -> Callable:
|
|
65
|
+
"""Wrap an individual async function with OAuth authorization."""
|
|
66
|
+
|
|
67
|
+
@wraps(func)
|
|
68
|
+
async def wrapper(*args, **kwargs):
|
|
69
|
+
global _verifiers
|
|
70
|
+
|
|
71
|
+
# Extract the Request object from kwargs
|
|
72
|
+
request: Request | None = kwargs.get("_rq")
|
|
73
|
+
|
|
74
|
+
if request is None:
|
|
75
|
+
_logger.error("Request object not found in function arguments")
|
|
76
|
+
raise HTTPException(status_code=500, detail="Internal server error")
|
|
77
|
+
|
|
78
|
+
# Check if authorization should be bypassed in local environment
|
|
79
|
+
if os.getenv("ENV") == "local":
|
|
80
|
+
_logger.info("OAuth authorization bypassed in local environment")
|
|
81
|
+
return await func(*args, **kwargs)
|
|
82
|
+
|
|
83
|
+
# Extract token from Authorization header
|
|
84
|
+
auth_header = request.headers.get("Authorization", "")
|
|
85
|
+
if not auth_header or not auth_header.startswith("Bearer "):
|
|
86
|
+
_logger.warning("Missing or invalid Authorization header")
|
|
87
|
+
raise HTTPException(status_code=401, detail="Missing or invalid authorization token")
|
|
88
|
+
|
|
89
|
+
token = auth_header.replace("Bearer ", "").strip()
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
# Get or create verifier for this config
|
|
93
|
+
config_key = _get_config_key(oauth_config)
|
|
94
|
+
if config_key not in _verifiers:
|
|
95
|
+
_verifiers[config_key] = OAuth2TokenVerifier(
|
|
96
|
+
domain=oauth_config.domain,
|
|
97
|
+
audience=oauth_config.audience,
|
|
98
|
+
algorithms=oauth_config.algorithms,
|
|
99
|
+
issuer=oauth_config.issuer,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
verifier = _verifiers[config_key]
|
|
103
|
+
payload = await verifier.verify_token(token)
|
|
104
|
+
|
|
105
|
+
# Verify scopes if required
|
|
106
|
+
if required_scopes:
|
|
107
|
+
verifier.verify_scopes(payload, required_scopes)
|
|
108
|
+
|
|
109
|
+
_logger.info(f"OAuth authorization successful for subject: {payload.get('sub', 'unknown')}")
|
|
110
|
+
|
|
111
|
+
# Call the original function
|
|
112
|
+
return await func(*args, **kwargs)
|
|
113
|
+
|
|
114
|
+
except TokenVerificationError as e:
|
|
115
|
+
_logger.warning(f"OAuth authorization failed: {e}")
|
|
116
|
+
raise HTTPException(status_code=403, detail=str(e))
|
|
117
|
+
except Exception as e:
|
|
118
|
+
_logger.error(f"Unexpected error during OAuth authorization: {e}")
|
|
119
|
+
raise HTTPException(status_code=500, detail="Authorization error")
|
|
120
|
+
|
|
121
|
+
return wrapper
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _wrap_class(cls: type, required_scopes: list[str], oauth_config: OAuthConfig) -> type:
|
|
125
|
+
"""Wrap all async methods in a class with OAuth authorization."""
|
|
126
|
+
|
|
127
|
+
# Get all methods from the class
|
|
128
|
+
for attr_name in dir(cls):
|
|
129
|
+
# Skip private/magic methods and non-callables
|
|
130
|
+
if attr_name.startswith("_"):
|
|
131
|
+
continue
|
|
132
|
+
|
|
133
|
+
attr = getattr(cls, attr_name)
|
|
134
|
+
|
|
135
|
+
# Check if it's a callable method (not a property or static attribute)
|
|
136
|
+
if callable(attr) and not isinstance(attr, (staticmethod, classmethod, property)):
|
|
137
|
+
# Wrap the method
|
|
138
|
+
wrapped = _wrap_function(attr, required_scopes, oauth_config)
|
|
139
|
+
setattr(cls, attr_name, wrapped)
|
|
140
|
+
|
|
141
|
+
return cls
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cezzis_oauth_fastapi
|
|
3
|
+
Version: 0.0.20
|
|
4
|
+
Summary: A lightweight, production-ready Python library for OAuth 2.0 authentication. Provides both **token acquisition** and **JWT verification** with enterprise-grade features including automatic token caching, refresh management, JWKS-based verification, and scope validation.
|
|
5
|
+
License: MIT
|
|
6
|
+
Author: mtnvencenzo
|
|
7
|
+
Author-email: rvecchi@gmail.com
|
|
8
|
+
Requires-Python: >=3.12,<3.15
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Requires-Dist: authlib (>=1.4.0,<2.0.0)
|
|
15
|
+
Requires-Dist: cezzis-oauth (>=0.0.19,<0.0.20)
|
|
16
|
+
Requires-Dist: fastapi[standard] (>=0.128.0,<0.129.0)
|
|
17
|
+
Requires-Dist: httpx (>=0.28.1,<0.29.0)
|
|
18
|
+
Requires-Dist: python-jose[cryptography] (>=3.5.0,<4.0.0)
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# Cezzis OAuth
|
|
22
|
+
|
|
23
|
+
[](https://www.python.org/downloads/)
|
|
24
|
+
[](https://opensource.org/licenses/MIT)
|
|
25
|
+
[](https://pypi.org/project/cezzis-oauth-fastapi/)
|
|
26
|
+
[](https://github.com/mtnvencenzo/cezzis-pycore/actions/workflows/cezzis-oauth-fastapi-cicd.yaml)
|
|
27
|
+
|
|
28
|
+
A lightweight, production-ready Python library for OAuth 2.0 authentication. Provides both **token acquisition** and **JWT verification** with enterprise-grade features including automatic token caching, refresh management, JWKS-based verification, and scope validation.
|
|
29
|
+
|
|
30
|
+
## 🚀 Installation
|
|
31
|
+
|
|
32
|
+
Install `cezzis-oauth-fastapi` from PyPI:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install cezzis-oauth-fastapi
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Or using Poetry:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
poetry add cezzis-oauth-fastapi
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## 📋 Requirements
|
|
45
|
+
|
|
46
|
+
- Python 3.12 or higher
|
|
47
|
+
|
|
48
|
+
## 📖 Documentation & Examples
|
|
49
|
+
|
|
50
|
+
Complete documentation, examples, and guides are available in the GitHub repository:
|
|
51
|
+
|
|
52
|
+
[Full Documentation & Examples](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/cezzis-oauth-fastapi/README.md)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
## 📄 License
|
|
56
|
+
|
|
57
|
+
This project is licensed under the MIT License. See the [LICENSE](https://github.com/mtnvencenzo/cezzis-pycore/blob/main/LICENSE) file for details.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
cezzis_oauth_fastapi/__init__.py,sha256=AYIgvpPVhfOZ4QHwWlkHZwMyCkA0DUwrnqMOAX_s340,491
|
|
2
|
+
cezzis_oauth_fastapi/__init__.pyi,sha256=xdg4BBUtom1KE4qmhE7nrDG5X1j3qCvWMztEq9iTaOo,219
|
|
3
|
+
cezzis_oauth_fastapi/oauth_authorization.py,sha256=a9DXYnHO4ID7rw5y7xYl1wf1jClocpBppYPuLHBPL9Q,5208
|
|
4
|
+
cezzis_oauth_fastapi/oauth_authorization.pyi,sha256=4geD4rO2v-gOr80e4E6q5g6Jl8zkADxMgqxZkkmsvh8,233
|
|
5
|
+
cezzis_oauth_fastapi/oauth_config.py,sha256=lUHSZW4ugwdlmpUwhY0F4FAEgEtur9-6eeX58GLFSuA,205
|
|
6
|
+
cezzis_oauth_fastapi/oauth_config.pyi,sha256=9Zp2lVp_Y_IiPXneTBUOGQ-0wYYQfUgkgAxNjuX5rzY,134
|
|
7
|
+
cezzis_oauth_fastapi-0.0.20.dist-info/METADATA,sha256=nWq56W_46TN4O18Q_o7jKOSFnpe6soDS0g1wP5kDVUs,2445
|
|
8
|
+
cezzis_oauth_fastapi-0.0.20.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
|
|
9
|
+
cezzis_oauth_fastapi-0.0.20.dist-info/RECORD,,
|