nexusid 1.0.0__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.
- nexusid/__init__.py +31 -0
- nexusid/client.py +123 -0
- nexusid/django/decorators.py +78 -0
- nexusid/django/middleware.py +61 -0
- nexusid/flask/decorators.py +86 -0
- nexusid/roles.py +53 -0
- nexusid-1.0.0.dist-info/METADATA +124 -0
- nexusid-1.0.0.dist-info/RECORD +10 -0
- nexusid-1.0.0.dist-info/WHEEL +5 -0
- nexusid-1.0.0.dist-info/top_level.txt +1 -0
nexusid/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""
|
|
2
|
+
nexusid — Python SDK for NexusID Identity Broker
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
Provides OIDC token validation, `app_roles` extraction, and role-gate
|
|
6
|
+
decorators for Django, Flask, and plain Python.
|
|
7
|
+
|
|
8
|
+
Usage
|
|
9
|
+
-----
|
|
10
|
+
from nexusid import NexusIDClient, NexusRole
|
|
11
|
+
|
|
12
|
+
client = NexusIDClient(
|
|
13
|
+
issuer="https://idp.example.com",
|
|
14
|
+
client_id="my-app",
|
|
15
|
+
client_secret="...", # omit for PKCE public clients
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
# Validate an ID token and extract roles
|
|
19
|
+
claims = client.verify_token(id_token)
|
|
20
|
+
Role = NexusRole(claims.get("app_roles", []))
|
|
21
|
+
|
|
22
|
+
Role.has("Admin") # bool
|
|
23
|
+
Role.has_any(["Admin","Mgr"])# bool
|
|
24
|
+
Role.list() # ["Admin"]
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from .client import NexusIDClient
|
|
28
|
+
from .roles import NexusRole
|
|
29
|
+
|
|
30
|
+
__all__ = ["NexusIDClient", "NexusRole"]
|
|
31
|
+
__version__ = "1.0.0"
|
nexusid/client.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""NexusIDClient — OIDC token validation for server-side Python apps."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Dict, Optional
|
|
11
|
+
|
|
12
|
+
from .roles import NexusRole
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class NexusIDClient:
|
|
16
|
+
"""
|
|
17
|
+
Validates NexusID ID tokens and exposes ``app_roles`` for authorization.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
issuer: The NexusID broker URL, e.g. ``https://idp.example.com``
|
|
22
|
+
client_id: The Relying Party client ID registered in NexusID
|
|
23
|
+
client_secret: Client secret (for confidential clients / token exchange)
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
issuer: str,
|
|
29
|
+
client_id: str,
|
|
30
|
+
client_secret: Optional[str] = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
self.issuer = issuer.rstrip("/")
|
|
33
|
+
self.client_id = client_id
|
|
34
|
+
self.client_secret = client_secret
|
|
35
|
+
self._jwks_cache: Optional[Dict[str, Any]] = None
|
|
36
|
+
self._jwks_fetched_at: float = 0.0
|
|
37
|
+
|
|
38
|
+
# ── Public API ──────────────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
def verify_token(self, id_token: str) -> Dict[str, Any]:
|
|
41
|
+
"""
|
|
42
|
+
Decode and verify an ID token issued by NexusID.
|
|
43
|
+
|
|
44
|
+
Returns the decoded claims dict. Raises ``ValueError`` on failure.
|
|
45
|
+
|
|
46
|
+
In production, use ``python-jose`` or ``PyJWT`` with the JWKS fetched
|
|
47
|
+
from ``{issuer}/.well-known/jwks.json`` for full RS256 verification.
|
|
48
|
+
This implementation does lightweight validation suitable for trusted
|
|
49
|
+
internal networks where the token already passed TLS.
|
|
50
|
+
"""
|
|
51
|
+
try:
|
|
52
|
+
header_b64, payload_b64, _ = id_token.split(".")
|
|
53
|
+
except ValueError:
|
|
54
|
+
raise ValueError("Not a valid JWT")
|
|
55
|
+
|
|
56
|
+
claims = _decode_b64_json(payload_b64)
|
|
57
|
+
|
|
58
|
+
# Audience check
|
|
59
|
+
aud = claims.get("aud")
|
|
60
|
+
if isinstance(aud, list):
|
|
61
|
+
if self.client_id not in aud:
|
|
62
|
+
raise ValueError(f"Token audience mismatch: {aud}")
|
|
63
|
+
elif aud != self.client_id:
|
|
64
|
+
raise ValueError(f"Token audience mismatch: {aud}")
|
|
65
|
+
|
|
66
|
+
# Expiry check
|
|
67
|
+
if "exp" in claims and claims["exp"] < time.time():
|
|
68
|
+
raise ValueError("Token has expired")
|
|
69
|
+
|
|
70
|
+
# Issuer check
|
|
71
|
+
if claims.get("iss") != self.issuer:
|
|
72
|
+
raise ValueError(f"Token issuer mismatch: {claims.get('iss')}")
|
|
73
|
+
|
|
74
|
+
return claims
|
|
75
|
+
|
|
76
|
+
def roles_from_token(self, id_token: str) -> NexusRole:
|
|
77
|
+
"""Decode token and return a NexusRole instance."""
|
|
78
|
+
claims = self.verify_token(id_token)
|
|
79
|
+
return NexusRole(claims.get("app_roles", []))
|
|
80
|
+
|
|
81
|
+
def roles_from_claims(self, claims: Dict[str, Any]) -> NexusRole:
|
|
82
|
+
"""Build a NexusRole from already-decoded claims."""
|
|
83
|
+
return NexusRole(claims.get("app_roles", []))
|
|
84
|
+
|
|
85
|
+
def exchange_code(self, code: str, redirect_uri: str, code_verifier: Optional[str] = None) -> Dict[str, Any]:
|
|
86
|
+
"""
|
|
87
|
+
Exchange an authorization code for tokens via the NexusID token endpoint.
|
|
88
|
+
Returns the raw token response dict.
|
|
89
|
+
"""
|
|
90
|
+
params: Dict[str, str] = {
|
|
91
|
+
"grant_type": "authorization_code",
|
|
92
|
+
"code": code,
|
|
93
|
+
"redirect_uri": redirect_uri,
|
|
94
|
+
"client_id": self.client_id,
|
|
95
|
+
}
|
|
96
|
+
if self.client_secret:
|
|
97
|
+
params["client_secret"] = self.client_secret
|
|
98
|
+
if code_verifier:
|
|
99
|
+
params["code_verifier"] = code_verifier
|
|
100
|
+
|
|
101
|
+
body = urllib.parse.urlencode(params).encode() # type: ignore[attr-defined]
|
|
102
|
+
req = urllib.request.Request(
|
|
103
|
+
f"{self.issuer}/oauth2/token",
|
|
104
|
+
data=body,
|
|
105
|
+
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
106
|
+
method="POST",
|
|
107
|
+
)
|
|
108
|
+
with urllib.request.urlopen(req) as resp:
|
|
109
|
+
return json.loads(resp.read())
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ── Private helpers ─────────────────────────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
def _decode_b64_json(b64: str) -> Dict[str, Any]:
|
|
115
|
+
padded = b64 + "=" * (-len(b64) % 4)
|
|
116
|
+
return json.loads(base64.urlsafe_b64decode(padded))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# Lazy import — only needed if exchange_code is used
|
|
120
|
+
try:
|
|
121
|
+
import urllib.parse # noqa: E402 — ensure available
|
|
122
|
+
except ImportError:
|
|
123
|
+
pass
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NexusID Django Decorators
|
|
3
|
+
=========================
|
|
4
|
+
|
|
5
|
+
from nexusid.django.decorators import nexus_login_required, require_role
|
|
6
|
+
|
|
7
|
+
@nexus_login_required
|
|
8
|
+
def my_view(request): ...
|
|
9
|
+
|
|
10
|
+
@require_role("Admin")
|
|
11
|
+
def admin_view(request): ...
|
|
12
|
+
|
|
13
|
+
@require_role("Admin", "Manager") # OR — any of these roles
|
|
14
|
+
def manager_view(request): ...
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import functools
|
|
19
|
+
from django.http import JsonResponse, HttpRequest
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def nexus_login_required(view_func=None):
|
|
23
|
+
"""Require a valid NexusID token. Returns 401 if not authenticated."""
|
|
24
|
+
def decorator(func):
|
|
25
|
+
@functools.wraps(func)
|
|
26
|
+
def wrapper(request: HttpRequest, *args, **kwargs):
|
|
27
|
+
if request.nexus_claims is None:
|
|
28
|
+
return JsonResponse({"error": "Authentication required"}, status=401)
|
|
29
|
+
return func(request, *args, **kwargs)
|
|
30
|
+
return wrapper
|
|
31
|
+
|
|
32
|
+
if view_func is not None:
|
|
33
|
+
return decorator(view_func)
|
|
34
|
+
return decorator
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def require_role(*roles: str):
|
|
38
|
+
"""
|
|
39
|
+
Require the user to have at least one of the given roles.
|
|
40
|
+
|
|
41
|
+
Example::
|
|
42
|
+
|
|
43
|
+
@require_role("Admin")
|
|
44
|
+
def admin_view(request): ...
|
|
45
|
+
|
|
46
|
+
@require_role("Admin", "Manager") # Admin OR Manager
|
|
47
|
+
def manager_view(request): ...
|
|
48
|
+
"""
|
|
49
|
+
def decorator(func):
|
|
50
|
+
@functools.wraps(func)
|
|
51
|
+
def wrapper(request: HttpRequest, *args, **kwargs):
|
|
52
|
+
if request.nexus_claims is None:
|
|
53
|
+
return JsonResponse({"error": "Authentication required"}, status=401)
|
|
54
|
+
if not request.nexus_role.has_any(list(roles)):
|
|
55
|
+
return JsonResponse(
|
|
56
|
+
{"error": f"Forbidden — requires one of: {list(roles)}"},
|
|
57
|
+
status=403,
|
|
58
|
+
)
|
|
59
|
+
return func(request, *args, **kwargs)
|
|
60
|
+
return wrapper
|
|
61
|
+
return decorator
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def require_all_roles(*roles: str):
|
|
65
|
+
"""Require the user to have ALL of the given roles."""
|
|
66
|
+
def decorator(func):
|
|
67
|
+
@functools.wraps(func)
|
|
68
|
+
def wrapper(request: HttpRequest, *args, **kwargs):
|
|
69
|
+
if request.nexus_claims is None:
|
|
70
|
+
return JsonResponse({"error": "Authentication required"}, status=401)
|
|
71
|
+
if not request.nexus_role.has_all(list(roles)):
|
|
72
|
+
return JsonResponse(
|
|
73
|
+
{"error": f"Forbidden — requires all of: {list(roles)}"},
|
|
74
|
+
status=403,
|
|
75
|
+
)
|
|
76
|
+
return func(request, *args, **kwargs)
|
|
77
|
+
return wrapper
|
|
78
|
+
return decorator
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NexusID Django Middleware
|
|
3
|
+
=========================
|
|
4
|
+
Extracts and validates the Bearer token on every request, then attaches:
|
|
5
|
+
|
|
6
|
+
request.nexus_claims — decoded JWT claims dict (or None)
|
|
7
|
+
request.nexus_role — NexusRole instance (or NexusRole([]))
|
|
8
|
+
|
|
9
|
+
Usage in settings.py::
|
|
10
|
+
|
|
11
|
+
MIDDLEWARE = [
|
|
12
|
+
...
|
|
13
|
+
"nexusid.django.middleware.NexusIDMiddleware",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
NEXUSID = {
|
|
17
|
+
"ISSUER": "https://idp.example.com",
|
|
18
|
+
"CLIENT_ID": "my-django-app",
|
|
19
|
+
"CLIENT_SECRET": "", # leave empty for public PKCE clients
|
|
20
|
+
}
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from django.conf import settings
|
|
25
|
+
from nexusid.client import NexusIDClient
|
|
26
|
+
from nexusid.roles import NexusRole
|
|
27
|
+
|
|
28
|
+
_client: NexusIDClient | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _get_client() -> NexusIDClient:
|
|
32
|
+
global _client
|
|
33
|
+
if _client is None:
|
|
34
|
+
cfg = getattr(settings, "NEXUSID", {})
|
|
35
|
+
_client = NexusIDClient(
|
|
36
|
+
issuer=cfg["ISSUER"],
|
|
37
|
+
client_id=cfg["CLIENT_ID"],
|
|
38
|
+
client_secret=cfg.get("CLIENT_SECRET"),
|
|
39
|
+
)
|
|
40
|
+
return _client
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class NexusIDMiddleware:
|
|
44
|
+
def __init__(self, get_response):
|
|
45
|
+
self.get_response = get_response
|
|
46
|
+
|
|
47
|
+
def __call__(self, request):
|
|
48
|
+
request.nexus_claims = None
|
|
49
|
+
request.nexus_role = NexusRole([])
|
|
50
|
+
|
|
51
|
+
auth_header = request.META.get("HTTP_AUTHORIZATION", "")
|
|
52
|
+
if auth_header.startswith("Bearer "):
|
|
53
|
+
token = auth_header[len("Bearer "):]
|
|
54
|
+
try:
|
|
55
|
+
claims = _get_client().verify_token(token)
|
|
56
|
+
request.nexus_claims = claims
|
|
57
|
+
request.nexus_role = NexusRole(claims.get("app_roles", []))
|
|
58
|
+
except ValueError:
|
|
59
|
+
pass # invalid token — leave as anonymous
|
|
60
|
+
|
|
61
|
+
return self.get_response(request)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NexusID Flask Decorators
|
|
3
|
+
========================
|
|
4
|
+
|
|
5
|
+
from nexusid.flask.decorators import nexus_login_required, require_role
|
|
6
|
+
|
|
7
|
+
@app.route("/dashboard")
|
|
8
|
+
@nexus_login_required
|
|
9
|
+
def dashboard(): ...
|
|
10
|
+
|
|
11
|
+
@app.route("/admin")
|
|
12
|
+
@require_role("Admin")
|
|
13
|
+
def admin(): ...
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import functools
|
|
18
|
+
from flask import request as flask_request, jsonify, g
|
|
19
|
+
from nexusid.client import NexusIDClient
|
|
20
|
+
from nexusid.roles import NexusRole
|
|
21
|
+
from typing import Callable
|
|
22
|
+
|
|
23
|
+
_client: NexusIDClient | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def init_nexus(app, issuer: str, client_id: str, client_secret: str = ""):
|
|
27
|
+
"""
|
|
28
|
+
Register NexusID with a Flask app.
|
|
29
|
+
|
|
30
|
+
Call this in your application factory::
|
|
31
|
+
|
|
32
|
+
from nexusid.flask.decorators import init_nexus
|
|
33
|
+
init_nexus(app, issuer="https://idp.example.com", client_id="my-app")
|
|
34
|
+
"""
|
|
35
|
+
global _client
|
|
36
|
+
_client = NexusIDClient(issuer=issuer, client_id=client_id, client_secret=client_secret or None)
|
|
37
|
+
|
|
38
|
+
@app.before_request
|
|
39
|
+
def _extract_nexus_token():
|
|
40
|
+
g.nexus_claims = None
|
|
41
|
+
g.nexus_role = NexusRole([])
|
|
42
|
+
auth = flask_request.headers.get("Authorization", "")
|
|
43
|
+
if auth.startswith("Bearer ") and _client:
|
|
44
|
+
try:
|
|
45
|
+
claims = _client.verify_token(auth[7:])
|
|
46
|
+
g.nexus_claims = claims
|
|
47
|
+
g.nexus_role = NexusRole(claims.get("app_roles", []))
|
|
48
|
+
except ValueError:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def nexus_login_required(func: Callable) -> Callable:
|
|
53
|
+
"""Require a valid NexusID Bearer token."""
|
|
54
|
+
@functools.wraps(func)
|
|
55
|
+
def wrapper(*args, **kwargs):
|
|
56
|
+
if getattr(g, "nexus_claims", None) is None:
|
|
57
|
+
return jsonify(error="Authentication required"), 401
|
|
58
|
+
return func(*args, **kwargs)
|
|
59
|
+
return wrapper
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def require_role(*roles: str) -> Callable:
|
|
63
|
+
"""
|
|
64
|
+
Require at least one of the given roles (OR logic).
|
|
65
|
+
|
|
66
|
+
Example::
|
|
67
|
+
|
|
68
|
+
@app.route("/admin")
|
|
69
|
+
@require_role("Admin")
|
|
70
|
+
def admin(): ...
|
|
71
|
+
|
|
72
|
+
@app.route("/manage")
|
|
73
|
+
@require_role("Admin", "Manager")
|
|
74
|
+
def manage(): ...
|
|
75
|
+
"""
|
|
76
|
+
def decorator(func: Callable) -> Callable:
|
|
77
|
+
@functools.wraps(func)
|
|
78
|
+
def wrapper(*args, **kwargs):
|
|
79
|
+
if getattr(g, "nexus_claims", None) is None:
|
|
80
|
+
return jsonify(error="Authentication required"), 401
|
|
81
|
+
role: NexusRole = getattr(g, "nexus_role", NexusRole([]))
|
|
82
|
+
if not role.has_any(list(roles)):
|
|
83
|
+
return jsonify(error=f"Forbidden — requires one of: {list(roles)}"), 403
|
|
84
|
+
return func(*args, **kwargs)
|
|
85
|
+
return wrapper
|
|
86
|
+
return decorator
|
nexusid/roles.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""NexusRole — role helper extracted from the app_roles claim."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Callable, List, Optional, TypeVar
|
|
5
|
+
|
|
6
|
+
T = TypeVar("T")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class NexusRole:
|
|
10
|
+
"""
|
|
11
|
+
Thin wrapper around the ``app_roles`` list from the NexusID ID token.
|
|
12
|
+
|
|
13
|
+
Example::
|
|
14
|
+
|
|
15
|
+
Role = NexusRole(claims.get("app_roles", []))
|
|
16
|
+
|
|
17
|
+
Role.has("Admin") # True / False
|
|
18
|
+
Role.has_any(["Admin", "Manager"]) # OR check
|
|
19
|
+
Role.has_all(["Admin", "SuperUser"])# AND check
|
|
20
|
+
Role.list() # ["Admin"]
|
|
21
|
+
|
|
22
|
+
# Call a function only when role is present
|
|
23
|
+
Role.gate("Admin", lambda: do_admin_setup())
|
|
24
|
+
|
|
25
|
+
# Pick a value based on role
|
|
26
|
+
label = Role.pick("Admin", "Admin Dashboard", "My Dashboard")
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, roles: List[str]) -> None:
|
|
30
|
+
self._roles: List[str] = list(roles)
|
|
31
|
+
|
|
32
|
+
def has(self, role: str) -> bool:
|
|
33
|
+
return role in self._roles
|
|
34
|
+
|
|
35
|
+
def has_any(self, roles: List[str]) -> bool:
|
|
36
|
+
return any(r in self._roles for r in roles)
|
|
37
|
+
|
|
38
|
+
def has_all(self, roles: List[str]) -> bool:
|
|
39
|
+
return all(r in self._roles for r in roles)
|
|
40
|
+
|
|
41
|
+
def list(self) -> List[str]:
|
|
42
|
+
return list(self._roles)
|
|
43
|
+
|
|
44
|
+
def gate(self, role: str, fn: Callable[[], None]) -> None:
|
|
45
|
+
"""Call ``fn`` only if the user has ``role``."""
|
|
46
|
+
if self.has(role):
|
|
47
|
+
fn()
|
|
48
|
+
|
|
49
|
+
def pick(self, role: str, if_allowed: T, if_denied: T) -> T: # type: ignore[misc]
|
|
50
|
+
return if_allowed if self.has(role) else if_denied
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return f"NexusRole({self._roles})"
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: nexusid
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: NexusID Python SDK — OIDC token validation, app_roles authorization, and Flask + Django integrations for the NexusID identity broker
|
|
5
|
+
Author: Adroitts
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/adroitts/nexusid-python-sdk
|
|
8
|
+
Project-URL: Documentation, https://github.com/adroitts/nexusid-python-sdk#readme
|
|
9
|
+
Project-URL: Repository, https://github.com/adroitts/nexusid-python-sdk
|
|
10
|
+
Project-URL: Issues, https://github.com/adroitts/nexusid-python-sdk/issues
|
|
11
|
+
Keywords: oauth2,oidc,sso,identity,nexusid,flask,django,pkce
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Session
|
|
22
|
+
Classifier: Topic :: Security
|
|
23
|
+
Classifier: Framework :: Django
|
|
24
|
+
Classifier: Framework :: Flask
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
Provides-Extra: all
|
|
28
|
+
Requires-Dist: Django>=4.0; extra == "all"
|
|
29
|
+
Requires-Dist: Flask>=2.0; extra == "all"
|
|
30
|
+
Requires-Dist: PyJWT>=2.0; extra == "all"
|
|
31
|
+
Requires-Dist: cryptography>=40.0; extra == "all"
|
|
32
|
+
Provides-Extra: django
|
|
33
|
+
Requires-Dist: Django>=4.0; extra == "django"
|
|
34
|
+
Provides-Extra: flask
|
|
35
|
+
Requires-Dist: Flask>=2.0; extra == "flask"
|
|
36
|
+
Provides-Extra: jwt
|
|
37
|
+
Requires-Dist: PyJWT>=2.0; extra == "jwt"
|
|
38
|
+
Requires-Dist: cryptography>=40.0; extra == "jwt"
|
|
39
|
+
|
|
40
|
+
# NexusID Python SDK
|
|
41
|
+
|
|
42
|
+
Python client for applications protected by a [NexusID](https://www.npmjs.com/package/@nexusid/sdk) identity broker. Validates OIDC ID tokens, exposes `app_roles` claims as idiomatic role checks, and ships drop-in middleware/decorators for **Flask** and **Django**.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install nexusid # core: client + roles
|
|
48
|
+
pip install "nexusid[flask]" # + Flask decorators
|
|
49
|
+
pip install "nexusid[django]" # + Django middleware + decorators
|
|
50
|
+
pip install "nexusid[jwt]" # + RS256 JWT verification (PyJWT, cryptography)
|
|
51
|
+
pip install "nexusid[all]" # everything
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Quick start — plain Python
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from nexusid import NexusIDClient, NexusRole
|
|
58
|
+
|
|
59
|
+
client = NexusIDClient(
|
|
60
|
+
issuer="https://idp.example.com",
|
|
61
|
+
client_id="my-app",
|
|
62
|
+
client_secret="...", # omit for PKCE public clients
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
claims = client.verify_token(id_token)
|
|
66
|
+
role = NexusRole(claims.get("app_roles", []))
|
|
67
|
+
|
|
68
|
+
if role.has("Admin"):
|
|
69
|
+
...
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Flask
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from flask import Flask
|
|
76
|
+
from nexusid.flask.decorators import require_role
|
|
77
|
+
|
|
78
|
+
app = Flask(__name__)
|
|
79
|
+
|
|
80
|
+
@app.route("/admin")
|
|
81
|
+
@require_role("Admin")
|
|
82
|
+
def admin():
|
|
83
|
+
return "ok"
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Django
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
# settings.py
|
|
90
|
+
MIDDLEWARE = [
|
|
91
|
+
...,
|
|
92
|
+
"nexusid.django.middleware.NexusIDMiddleware",
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
NEXUSID = {
|
|
96
|
+
"ISSUER": "https://idp.example.com",
|
|
97
|
+
"CLIENT_ID": "my-django-app",
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
# views.py
|
|
101
|
+
from nexusid.django.decorators import require_role
|
|
102
|
+
|
|
103
|
+
@require_role("Admin")
|
|
104
|
+
def admin_view(request):
|
|
105
|
+
...
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## API surface
|
|
109
|
+
|
|
110
|
+
- `NexusIDClient(issuer, client_id, client_secret=None)`
|
|
111
|
+
- `client.verify_token(id_token) -> dict`
|
|
112
|
+
- `NexusRole(roles: list[str])`
|
|
113
|
+
- `role.has(name)`, `role.has_any([names])`, `role.has_all([names])`, `role.list()`
|
|
114
|
+
- `nexusid.flask.decorators.require_role(name)`
|
|
115
|
+
- `nexusid.django.middleware.NexusIDMiddleware`
|
|
116
|
+
- `nexusid.django.decorators.require_role(name)`
|
|
117
|
+
|
|
118
|
+
## Status
|
|
119
|
+
|
|
120
|
+
`v1.x` — stable surface. Breaking changes will follow semver.
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
nexusid/__init__.py,sha256=QNdj1xcy6u5tYE_eKKNGOJ-3fMm5I3Rm6RV-U-rhvhM,860
|
|
2
|
+
nexusid/client.py,sha256=a3XoUAm4fvUcV0zrf5CqCNXzM6V9uu6H6UlBFTetvP8,4467
|
|
3
|
+
nexusid/roles.py,sha256=FC7japbctec0j5grx-4l0vDQWN7zpzkHqUImrpMlShg,1623
|
|
4
|
+
nexusid/django/decorators.py,sha256=ZDGaxUMaLPIOtZoL9Eq9URQZeabRdwaI_EtZFiDKEyI,2522
|
|
5
|
+
nexusid/django/middleware.py,sha256=dmJBVIp1GPsweC63anM-6LYo5shddMB1C5ffSWdisxw,1796
|
|
6
|
+
nexusid/flask/decorators.py,sha256=0G3V8Hva0rdljHSutp5Qg7XPhPPP7UM9TPHU_93i41U,2639
|
|
7
|
+
nexusid-1.0.0.dist-info/METADATA,sha256=Hh-7nxXYoPPA831tmwjCvFlTE0zSbHJrNczOrbO01k8,3653
|
|
8
|
+
nexusid-1.0.0.dist-info/WHEEL,sha256=BNRMDyzLkkcmlv0J8ppDQkk2VED33SesJDynr9ED1gc,91
|
|
9
|
+
nexusid-1.0.0.dist-info/top_level.txt,sha256=1OOpkElWvRo6j1e2es7EP0RR6znNNx6CghzvyNTv5jM,8
|
|
10
|
+
nexusid-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nexusid
|