dsm-oauth-admin-client 0.1.0__tar.gz

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.
Files changed (22) hide show
  1. dsm_oauth_admin_client-0.1.0/PKG-INFO +73 -0
  2. dsm_oauth_admin_client-0.1.0/README.md +63 -0
  3. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/__init__.py +1 -0
  4. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/apps.py +7 -0
  5. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/auth.py +89 -0
  6. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/middleware.py +19 -0
  7. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/migrations/0001_initial.py +45 -0
  8. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/migrations/__init__.py +0 -0
  9. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/models.py +22 -0
  10. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/services.py +82 -0
  11. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/templates/admin/login.html +11 -0
  12. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/tests.py +73 -0
  13. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/token_validation.py +76 -0
  14. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/urls.py +11 -0
  15. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client/views.py +196 -0
  16. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client.egg-info/PKG-INFO +73 -0
  17. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client.egg-info/SOURCES.txt +20 -0
  18. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client.egg-info/dependency_links.txt +1 -0
  19. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client.egg-info/requires.txt +3 -0
  20. dsm_oauth_admin_client-0.1.0/dsm_oauth_admin_client.egg-info/top_level.txt +1 -0
  21. dsm_oauth_admin_client-0.1.0/pyproject.toml +22 -0
  22. dsm_oauth_admin_client-0.1.0/setup.cfg +4 -0
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: dsm-oauth-admin-client
3
+ Version: 0.1.0
4
+ Summary: Django client integration for DSM OAuth and Django Admin
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: Django>=4.2
8
+ Requires-Dist: PyJWT[crypto]<3,>=2.8
9
+ Requires-Dist: requests>=2.32.3
10
+
11
+ # DSM OAuth Admin Client
12
+
13
+ Installable Django app that simulates a relying client for this repository's DSM OAuth provider. It adds Authorization Code + PKCE login and Django Admin session creation.
14
+
15
+ ## Install from this repository
16
+
17
+ ```sh
18
+ pip install ./packages/dsm-oauth-admin-client
19
+ ```
20
+
21
+ ## Configure a Django client
22
+
23
+ Register a confidential OAuth application in DSM OAuth. Set its redirect URI to `https://client.example.test/oauth-admin/callback/` and grant the `profile` scope.
24
+
25
+ Add the app before `django.contrib.admin` so its admin login template takes precedence:
26
+
27
+ ```python
28
+ INSTALLED_APPS = [
29
+ "dsm_oauth_admin_client",
30
+ "django.contrib.admin",
31
+ # ...
32
+ ]
33
+
34
+ DSM_OAUTH_SERVER_URL = "https://oauth.example.test"
35
+ DSM_OAUTH_ISSUER = "https://oauth.example.test" # Set when issuer differs from server URL.
36
+ DSM_OAUTH_CLIENT_ID = "client-id"
37
+ DSM_OAUTH_CLIENT_SECRET = "read-from-environment"
38
+ DSM_OAUTH_CALLBACK_URL = "https://client.example.test/oauth-admin/callback/"
39
+ DSM_OAUTH_VERIFY_SSL = True
40
+ ```
41
+
42
+ Include the client routes:
43
+
44
+ ```python
45
+ from django.urls import include, path
46
+
47
+ urlpatterns = [
48
+ path("oauth-admin/", include("dsm_oauth_admin_client.urls")),
49
+ path("admin/", admin.site.urls),
50
+ ]
51
+ ```
52
+
53
+ To refresh tokens and synchronize staff access on authenticated requests, add the middleware after Django's `AuthenticationMiddleware`:
54
+
55
+ ```python
56
+ MIDDLEWARE = [
57
+ # ...
58
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
59
+ "dsm_oauth_admin_client.middleware.OAuthSessionValidationMiddleware",
60
+ # ...
61
+ ]
62
+ ```
63
+
64
+ The package keeps OAuth tokens in the Django session and maps provider profile fields `id`/`sub`, `username`, `email`, `first_name`, `last_name`, `is_active`, `is_staff`, and `is_superuser` to the local user. Only active staff users can enter Admin.
65
+
66
+ The callback fetches `/api/account/` once to create the local Django user. The middleware then verifies access-token signatures locally using the provider's `/api/access-token-jwks/` endpoint, refreshes expired tokens through `/o/token/`, and applies staff flags from verified token claims. It does not call the provider on every request. Role changes and token revocation are observed when the access token refreshes, so the delay can be up to the access-token lifetime. Logout attempts to revoke access and refresh tokens, clears the local Django session, then redirects through provider `/logout/`. If the provider is unavailable, local logout still completes; server-side tokens remain until revoked or expired.
67
+
68
+ Account linking uses the provider's stable `sub` (or `id`) plus issuer URL, not the mutable username. Existing local users are not linked by matching username; a separate local account is created if that username is already taken. Run `python manage.py migrate` after installing the app.
69
+
70
+ Set `DSM_OAUTH_ISSUER` to the exact token issuer if it differs from `DSM_OAUTH_SERVER_URL`. Set `DSM_OAUTH_JWKS_URL` only when the provider's access-token JWKS endpoint uses a custom URL.
71
+
72
+ Do not expose the client secret to browser code. Use HTTPS and a protected Django session backend in production.
73
+ The package rejects Django's signed-cookie session backend because browser-readable cookies would contain OAuth tokens. On HTTPS deployments, set `SESSION_COOKIE_SECURE = True`, `SESSION_COOKIE_HTTPONLY = True`, `CSRF_COOKIE_SECURE = True`, and `SESSION_COOKIE_SAMESITE = "Lax"`.
@@ -0,0 +1,63 @@
1
+ # DSM OAuth Admin Client
2
+
3
+ Installable Django app that simulates a relying client for this repository's DSM OAuth provider. It adds Authorization Code + PKCE login and Django Admin session creation.
4
+
5
+ ## Install from this repository
6
+
7
+ ```sh
8
+ pip install ./packages/dsm-oauth-admin-client
9
+ ```
10
+
11
+ ## Configure a Django client
12
+
13
+ Register a confidential OAuth application in DSM OAuth. Set its redirect URI to `https://client.example.test/oauth-admin/callback/` and grant the `profile` scope.
14
+
15
+ Add the app before `django.contrib.admin` so its admin login template takes precedence:
16
+
17
+ ```python
18
+ INSTALLED_APPS = [
19
+ "dsm_oauth_admin_client",
20
+ "django.contrib.admin",
21
+ # ...
22
+ ]
23
+
24
+ DSM_OAUTH_SERVER_URL = "https://oauth.example.test"
25
+ DSM_OAUTH_ISSUER = "https://oauth.example.test" # Set when issuer differs from server URL.
26
+ DSM_OAUTH_CLIENT_ID = "client-id"
27
+ DSM_OAUTH_CLIENT_SECRET = "read-from-environment"
28
+ DSM_OAUTH_CALLBACK_URL = "https://client.example.test/oauth-admin/callback/"
29
+ DSM_OAUTH_VERIFY_SSL = True
30
+ ```
31
+
32
+ Include the client routes:
33
+
34
+ ```python
35
+ from django.urls import include, path
36
+
37
+ urlpatterns = [
38
+ path("oauth-admin/", include("dsm_oauth_admin_client.urls")),
39
+ path("admin/", admin.site.urls),
40
+ ]
41
+ ```
42
+
43
+ To refresh tokens and synchronize staff access on authenticated requests, add the middleware after Django's `AuthenticationMiddleware`:
44
+
45
+ ```python
46
+ MIDDLEWARE = [
47
+ # ...
48
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
49
+ "dsm_oauth_admin_client.middleware.OAuthSessionValidationMiddleware",
50
+ # ...
51
+ ]
52
+ ```
53
+
54
+ The package keeps OAuth tokens in the Django session and maps provider profile fields `id`/`sub`, `username`, `email`, `first_name`, `last_name`, `is_active`, `is_staff`, and `is_superuser` to the local user. Only active staff users can enter Admin.
55
+
56
+ The callback fetches `/api/account/` once to create the local Django user. The middleware then verifies access-token signatures locally using the provider's `/api/access-token-jwks/` endpoint, refreshes expired tokens through `/o/token/`, and applies staff flags from verified token claims. It does not call the provider on every request. Role changes and token revocation are observed when the access token refreshes, so the delay can be up to the access-token lifetime. Logout attempts to revoke access and refresh tokens, clears the local Django session, then redirects through provider `/logout/`. If the provider is unavailable, local logout still completes; server-side tokens remain until revoked or expired.
57
+
58
+ Account linking uses the provider's stable `sub` (or `id`) plus issuer URL, not the mutable username. Existing local users are not linked by matching username; a separate local account is created if that username is already taken. Run `python manage.py migrate` after installing the app.
59
+
60
+ Set `DSM_OAUTH_ISSUER` to the exact token issuer if it differs from `DSM_OAUTH_SERVER_URL`. Set `DSM_OAUTH_JWKS_URL` only when the provider's access-token JWKS endpoint uses a custom URL.
61
+
62
+ Do not expose the client secret to browser code. Use HTTPS and a protected Django session backend in production.
63
+ The package rejects Django's signed-cookie session backend because browser-readable cookies would contain OAuth tokens. On HTTPS deployments, set `SESSION_COOKIE_SECURE = True`, `SESSION_COOKIE_HTTPONLY = True`, `CSRF_COOKIE_SECURE = True`, and `SESSION_COOKIE_SAMESITE = "Lax"`.
@@ -0,0 +1 @@
1
+ """Django client integration for DSM OAuth."""
@@ -0,0 +1,7 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DsmOAuthAdminClientConfig(AppConfig):
5
+ default_auto_field = "django.db.models.BigAutoField"
6
+ name = "dsm_oauth_admin_client"
7
+ verbose_name = "DSM OAuth Admin Client"
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import jwt
6
+ import requests
7
+ from django.conf import settings
8
+ from django.contrib.auth import logout as django_logout
9
+ from django.http import HttpRequest
10
+
11
+ from .token_validation import verify_access_token
12
+ from .views import _client_auth, _provider_url
13
+
14
+
15
+ def _refresh_access_token(request: HttpRequest) -> bool | None:
16
+ refresh_token = request.session.get("dsm_oauth_refresh_token")
17
+ if not refresh_token:
18
+ return False
19
+ try:
20
+ response = requests.post(
21
+ _provider_url("/o/token/"),
22
+ auth=_client_auth(),
23
+ data={"grant_type": "refresh_token", "refresh_token": refresh_token},
24
+ timeout=15,
25
+ verify=getattr(settings, "DSM_OAUTH_VERIFY_SSL", True),
26
+ )
27
+ except requests.RequestException:
28
+ return None
29
+ if response.status_code == 429 or response.status_code >= 500:
30
+ return None
31
+ if response.status_code != 200:
32
+ return False
33
+ try:
34
+ tokens = response.json()
35
+ except ValueError:
36
+ return False
37
+ access_token = tokens.get("access_token") if isinstance(tokens, dict) else None
38
+ if not isinstance(access_token, str) or not access_token:
39
+ return False
40
+ request.session["dsm_oauth_access_token"] = access_token
41
+ rotated_refresh = tokens.get("refresh_token")
42
+ if isinstance(rotated_refresh, str) and rotated_refresh:
43
+ request.session["dsm_oauth_refresh_token"] = rotated_refresh
44
+ request.session.save()
45
+ return True
46
+
47
+
48
+ def ensure_oauth_session(request: HttpRequest) -> dict[str, Any] | None:
49
+ """Refresh identity and staff permissions from the provider when reachable."""
50
+ account = request.session.get("dsm_oauth_account")
51
+ access_token = request.session.get("dsm_oauth_access_token")
52
+ if not isinstance(account, dict) or not access_token:
53
+ return None
54
+
55
+ subject = str(account.get("sub") or account.get("id") or "").strip()
56
+ if not subject:
57
+ django_logout(request)
58
+ return None
59
+
60
+ try:
61
+ claims = verify_access_token(access_token, expected_subject=subject)
62
+ except jwt.PyJWKClientConnectionError:
63
+ # Keep the authenticated Django session if the key service is temporarily down.
64
+ return account
65
+ except (jwt.PyJWTError, jwt.PyJWKClientError):
66
+ refreshed = _refresh_access_token(request)
67
+ if refreshed is None:
68
+ return account
69
+ if not refreshed:
70
+ django_logout(request)
71
+ return None
72
+ try:
73
+ claims = verify_access_token(
74
+ request.session["dsm_oauth_access_token"],
75
+ expected_subject=subject,
76
+ )
77
+ except jwt.PyJWKClientConnectionError:
78
+ return account
79
+ except (jwt.PyJWTError, jwt.PyJWKClientError):
80
+ django_logout(request)
81
+ return None
82
+
83
+ request.user.is_active = claims["is_active"]
84
+ request.user.is_staff = claims["is_staff"]
85
+ request.user.is_superuser = claims["is_superuser"]
86
+ if not request.user.is_active or not request.user.is_staff:
87
+ django_logout(request)
88
+ return None
89
+ return account
@@ -0,0 +1,19 @@
1
+ from django.http import HttpRequest, HttpResponse
2
+
3
+ from .auth import ensure_oauth_session
4
+
5
+
6
+ class OAuthSessionValidationMiddleware:
7
+ """Validate OAuth-backed Django sessions after AuthenticationMiddleware."""
8
+
9
+ def __init__(self, get_response):
10
+ self.get_response = get_response
11
+
12
+ def __call__(self, request: HttpRequest) -> HttpResponse:
13
+ if (
14
+ getattr(request, "user", None)
15
+ and request.user.is_authenticated
16
+ and request.session.get("dsm_oauth_access_token")
17
+ ):
18
+ ensure_oauth_session(request)
19
+ return self.get_response(request)
@@ -0,0 +1,45 @@
1
+ from django.conf import settings
2
+ from django.db import migrations, models
3
+ import django.db.models.deletion
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+ initial = True
8
+
9
+ dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
10
+
11
+ operations = [
12
+ migrations.CreateModel(
13
+ name="OAuthIdentity",
14
+ fields=[
15
+ (
16
+ "id",
17
+ models.BigAutoField(
18
+ auto_created=True,
19
+ primary_key=True,
20
+ serialize=False,
21
+ verbose_name="ID",
22
+ ),
23
+ ),
24
+ ("issuer", models.URLField(max_length=255)),
25
+ ("subject", models.CharField(max_length=255)),
26
+ ("created_at", models.DateTimeField(auto_now_add=True)),
27
+ ("updated_at", models.DateTimeField(auto_now=True)),
28
+ (
29
+ "user",
30
+ models.ForeignKey(
31
+ on_delete=django.db.models.deletion.CASCADE,
32
+ related_name="dsm_oauth_identities",
33
+ to=settings.AUTH_USER_MODEL,
34
+ ),
35
+ ),
36
+ ],
37
+ ),
38
+ migrations.AddConstraint(
39
+ model_name="oauthidentity",
40
+ constraint=models.UniqueConstraint(
41
+ fields=("issuer", "subject"),
42
+ name="dsm_oauth_identity_issuer_subject_uniq",
43
+ ),
44
+ ),
45
+ ]
@@ -0,0 +1,22 @@
1
+ from django.conf import settings
2
+ from django.db import models
3
+
4
+
5
+ class OAuthIdentity(models.Model):
6
+ issuer = models.URLField(max_length=255)
7
+ subject = models.CharField(max_length=255)
8
+ user = models.ForeignKey(
9
+ settings.AUTH_USER_MODEL,
10
+ on_delete=models.CASCADE,
11
+ related_name="dsm_oauth_identities",
12
+ )
13
+ created_at = models.DateTimeField(auto_now_add=True)
14
+ updated_at = models.DateTimeField(auto_now=True)
15
+
16
+ class Meta:
17
+ constraints = [
18
+ models.UniqueConstraint(
19
+ fields=("issuer", "subject"),
20
+ name="dsm_oauth_identity_issuer_subject_uniq",
21
+ )
22
+ ]
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ from typing import Any
5
+
6
+ from django.conf import settings
7
+ from django.contrib.auth import get_user_model
8
+ from django.db import IntegrityError, transaction
9
+
10
+ from .models import OAuthIdentity
11
+
12
+
13
+ def _issuer() -> str:
14
+ issuer = getattr(settings, "DSM_OAUTH_ISSUER", None)
15
+ return (issuer or settings.DSM_OAUTH_SERVER_URL).rstrip("/")
16
+
17
+
18
+ def _subject(account: dict[str, Any]) -> str:
19
+ return str(account.get("sub") or account.get("id") or "").strip()
20
+
21
+
22
+ def _new_local_user(account: dict[str, Any]):
23
+ user_model = get_user_model()
24
+ username_field = user_model.USERNAME_FIELD
25
+ field = user_model._meta.get_field(username_field)
26
+ preferred = str(account.get("username") or "oauth-user").strip() or "oauth-user"
27
+ subject = _subject(account)
28
+ suffix = hashlib.sha256(f"{_issuer()}|{subject}".encode()).hexdigest()[:12]
29
+ candidate = preferred[: field.max_length]
30
+ lookup = {f"{username_field}__iexact": candidate}
31
+ if user_model._default_manager.filter(**lookup).exists():
32
+ suffix_text = f"-{suffix}"
33
+ candidate = f"{preferred[: field.max_length - len(suffix_text)]}{suffix_text}"
34
+ lookup[f"{username_field}__iexact"] = candidate
35
+ if user_model._default_manager.filter(**lookup).exists():
36
+ raise ValueError("Could not create a unique local username for OAuth account.")
37
+
38
+ user = user_model(**{username_field: candidate})
39
+ user.set_unusable_password()
40
+ return user
41
+
42
+
43
+ @transaction.atomic
44
+ def sync_oauth_user(account: dict[str, Any]):
45
+ subject = _subject(account)
46
+ if not subject or len(subject) > 255:
47
+ return None
48
+
49
+ issuer = _issuer()
50
+ identity = OAuthIdentity.objects.select_related("user").filter(
51
+ issuer=issuer, subject=subject
52
+ ).first()
53
+ user = identity.user if identity else _new_local_user(account)
54
+
55
+ user.email = str(account.get("email") or "")
56
+ user.first_name = str(account.get("first_name") or "")
57
+ user.last_name = str(account.get("last_name") or "")
58
+ if "is_active" in account:
59
+ user.is_active = bool(account["is_active"])
60
+ user.is_superuser = bool(account.get("is_superuser"))
61
+ user.is_staff = bool(account.get("is_staff") or user.is_superuser)
62
+ user.save()
63
+
64
+ if identity is None:
65
+ try:
66
+ with transaction.atomic():
67
+ OAuthIdentity.objects.create(issuer=issuer, subject=subject, user=user)
68
+ except IntegrityError:
69
+ user.delete()
70
+ identity = OAuthIdentity.objects.select_related("user").get(
71
+ issuer=issuer, subject=subject
72
+ )
73
+ user = identity.user
74
+ user.email = str(account.get("email") or "")
75
+ user.first_name = str(account.get("first_name") or "")
76
+ user.last_name = str(account.get("last_name") or "")
77
+ if "is_active" in account:
78
+ user.is_active = bool(account["is_active"])
79
+ user.is_superuser = bool(account.get("is_superuser"))
80
+ user.is_staff = bool(account.get("is_staff") or user.is_superuser)
81
+ user.save()
82
+ return user
@@ -0,0 +1,11 @@
1
+ {% extends "admin/base_site.html" %}
2
+ {% load i18n %}
3
+ {% block content %}
4
+ <div id="content-main">
5
+ <div style="text-align:center; margin-top:2rem;">
6
+ <a href="{% url 'dsm_oauth_admin_client:login' %}?next=/admin/" class="button">
7
+ {% translate "Login with DSM OAuth" %}
8
+ </a>
9
+ </div>
10
+ </div>
11
+ {% endblock %}
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from types import SimpleNamespace
5
+ from unittest.mock import patch
6
+
7
+ import jwt
8
+ from cryptography.hazmat.primitives.asymmetric import rsa
9
+ from django.test import SimpleTestCase, override_settings
10
+
11
+ from .token_validation import verify_access_token
12
+
13
+
14
+ class AccessTokenValidationTests(SimpleTestCase):
15
+ def setUp(self):
16
+ self.private_key = rsa.generate_private_key(
17
+ public_exponent=65537, key_size=2048
18
+ )
19
+ self.claims = {
20
+ "iss": "https://oauth.example.test",
21
+ "sub": "account-42",
22
+ "aud": "client-123",
23
+ "client_id": "client-123",
24
+ "scope": "profile",
25
+ "is_active": True,
26
+ "is_staff": True,
27
+ "is_superuser": False,
28
+ "iat": int(time.time()),
29
+ "exp": int(time.time()) + 300,
30
+ "jti": "test-token-id",
31
+ }
32
+ self.token = jwt.encode(
33
+ self.claims,
34
+ self.private_key,
35
+ algorithm="RS256",
36
+ headers={"typ": "at+jwt", "kid": "test-key"},
37
+ )
38
+
39
+ @override_settings(
40
+ DSM_OAUTH_SERVER_URL="https://oauth.example.test",
41
+ DSM_OAUTH_ISSUER="https://oauth.example.test",
42
+ DSM_OAUTH_CLIENT_ID="client-123",
43
+ DSM_OAUTH_VERIFY_SSL=True,
44
+ )
45
+ @patch("dsm_oauth_admin_client.token_validation._jwks_client")
46
+ def test_verifies_signature_issuer_audience_scope_and_subject(self, get_jwks):
47
+ jwks = get_jwks.return_value
48
+ jwks.get_signing_key_from_jwt.return_value = SimpleNamespace(
49
+ key=self.private_key.public_key()
50
+ )
51
+
52
+ claims = verify_access_token(self.token, expected_subject="account-42")
53
+
54
+ self.assertEqual(claims["sub"], "account-42")
55
+ self.assertTrue(claims["is_staff"])
56
+ get_jwks.assert_called_once_with(
57
+ "https://oauth.example.test/api/access-token-jwks/", True
58
+ )
59
+
60
+ @override_settings(
61
+ DSM_OAUTH_SERVER_URL="https://oauth.example.test",
62
+ DSM_OAUTH_ISSUER="https://oauth.example.test",
63
+ DSM_OAUTH_CLIENT_ID="client-123",
64
+ DSM_OAUTH_VERIFY_SSL=True,
65
+ )
66
+ @patch("dsm_oauth_admin_client.token_validation._jwks_client")
67
+ def test_rejects_a_different_session_subject(self, get_jwks):
68
+ get_jwks.return_value.get_signing_key_from_jwt.return_value = SimpleNamespace(
69
+ key=self.private_key.public_key()
70
+ )
71
+
72
+ with self.assertRaises(jwt.InvalidTokenError):
73
+ verify_access_token(self.token, expected_subject="different-account")
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ from functools import lru_cache
5
+ from typing import Any
6
+
7
+ import jwt
8
+ from django.conf import settings
9
+
10
+
11
+ @lru_cache(maxsize=8)
12
+ def _jwks_client(url: str, verify_ssl: bool) -> jwt.PyJWKClient:
13
+ ssl_context = ssl.create_default_context()
14
+ if not verify_ssl:
15
+ ssl_context.check_hostname = False
16
+ ssl_context.verify_mode = ssl.CERT_NONE
17
+ return jwt.PyJWKClient(
18
+ url,
19
+ cache_jwk_set=True,
20
+ lifespan=300,
21
+ ssl_context=ssl_context,
22
+ timeout=15,
23
+ )
24
+
25
+
26
+ def verify_access_token(
27
+ token: str, expected_subject: str | None = None
28
+ ) -> dict[str, Any]:
29
+ header = jwt.get_unverified_header(token)
30
+ if header.get("typ") != "at+jwt" or header.get("alg") != "RS256":
31
+ raise jwt.InvalidTokenError("Unexpected access token type or algorithm.")
32
+
33
+ server_url = settings.DSM_OAUTH_SERVER_URL.rstrip("/")
34
+ jwks_url = getattr(
35
+ settings,
36
+ "DSM_OAUTH_JWKS_URL",
37
+ f"{server_url}/api/access-token-jwks/",
38
+ )
39
+ signing_key = _jwks_client(
40
+ jwks_url, bool(getattr(settings, "DSM_OAUTH_VERIFY_SSL", True))
41
+ ).get_signing_key_from_jwt(token).key
42
+ issuer = getattr(settings, "DSM_OAUTH_ISSUER", server_url).rstrip("/")
43
+ claims = jwt.decode(
44
+ token,
45
+ signing_key,
46
+ algorithms=["RS256"],
47
+ audience=settings.DSM_OAUTH_CLIENT_ID,
48
+ issuer=issuer,
49
+ options={
50
+ "require": [
51
+ "aud",
52
+ "client_id",
53
+ "exp",
54
+ "iat",
55
+ "is_active",
56
+ "is_staff",
57
+ "is_superuser",
58
+ "iss",
59
+ "jti",
60
+ "scope",
61
+ "sub",
62
+ ]
63
+ },
64
+ )
65
+ if expected_subject is not None and str(claims["sub"]) != expected_subject:
66
+ raise jwt.InvalidTokenError("Access token subject does not match the session.")
67
+ if not isinstance(claims["scope"], str) or "profile" not in claims["scope"].split():
68
+ raise jwt.InvalidTokenError("Access token does not include the profile scope.")
69
+ if any(
70
+ not isinstance(claims[name], bool)
71
+ for name in ("is_active", "is_staff", "is_superuser")
72
+ ):
73
+ raise jwt.InvalidTokenError("Access token role claims are invalid.")
74
+ if not isinstance(claims["client_id"], str) or claims["client_id"] != settings.DSM_OAUTH_CLIENT_ID:
75
+ raise jwt.InvalidTokenError("Access token client does not match this client.")
76
+ return claims
@@ -0,0 +1,11 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ app_name = "dsm_oauth_admin_client"
6
+
7
+ urlpatterns = [
8
+ path("login/", views.login, name="login"),
9
+ path("callback/", views.callback, name="callback"),
10
+ path("logout/", views.logout, name="logout"),
11
+ ]
@@ -0,0 +1,196 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import secrets
6
+ from urllib.parse import urlencode
7
+
8
+ import jwt
9
+ import requests
10
+ from django.conf import settings
11
+ from django.contrib.auth import login as django_login, logout as django_logout
12
+ from django.core.exceptions import ImproperlyConfigured
13
+ from django.http import HttpRequest, HttpResponse, JsonResponse
14
+ from django.shortcuts import redirect
15
+ from django.urls import reverse
16
+ from django.utils.http import url_has_allowed_host_and_scheme
17
+ from django.views.decorators.http import require_GET
18
+
19
+ from .services import sync_oauth_user
20
+ from .token_validation import verify_access_token
21
+
22
+
23
+ def _setting(name: str, default=None):
24
+ value = getattr(settings, name, default)
25
+ if value is None:
26
+ raise ImproperlyConfigured(f"{name} must be configured for DSM OAuth.")
27
+ return value
28
+
29
+
30
+ def _provider_url(path: str) -> str:
31
+ return f"{_setting('DSM_OAUTH_SERVER_URL').rstrip('/')}/{path.lstrip('/')}"
32
+
33
+
34
+ def _callback_uri() -> str:
35
+ configured = getattr(settings, "DSM_OAUTH_CALLBACK_URL", "")
36
+ return configured or settings.SITE_URL.rstrip("/") + reverse(
37
+ "dsm_oauth_admin_client:callback"
38
+ )
39
+
40
+
41
+ def _client_auth() -> tuple[str, str]:
42
+ return (
43
+ _setting("DSM_OAUTH_CLIENT_ID"),
44
+ _setting("DSM_OAUTH_CLIENT_SECRET"),
45
+ )
46
+
47
+
48
+ def _safe_next(request: HttpRequest, value: str | None) -> str:
49
+ if value and url_has_allowed_host_and_scheme(
50
+ value, allowed_hosts={request.get_host()}, require_https=request.is_secure()
51
+ ):
52
+ return value
53
+ fallback = getattr(settings, "DSM_OAUTH_DEFAULT_REDIRECT_URL", "/admin/")
54
+ if url_has_allowed_host_and_scheme(
55
+ fallback, allowed_hosts={request.get_host()}, require_https=request.is_secure()
56
+ ):
57
+ return fallback
58
+ return "/admin/"
59
+
60
+
61
+ def _require_server_side_sessions() -> None:
62
+ if getattr(settings, "SESSION_ENGINE", "django.contrib.sessions.backends.db") == (
63
+ "django.contrib.sessions.backends.signed_cookies"
64
+ ):
65
+ raise ImproperlyConfigured(
66
+ "DSM OAuth tokens require a server-side Django session backend."
67
+ )
68
+
69
+
70
+ def _pkce_challenge(verifier: str) -> str:
71
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
72
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
73
+
74
+
75
+ @require_GET
76
+ def login(request: HttpRequest) -> HttpResponse:
77
+ _require_server_side_sessions()
78
+ state = secrets.token_urlsafe(32)
79
+ verifier = secrets.token_urlsafe(64)
80
+ request.session["dsm_oauth_state"] = state
81
+ request.session["dsm_oauth_verifier"] = verifier
82
+ request.session["dsm_oauth_next"] = _safe_next(request, request.GET.get("next"))
83
+ params = {
84
+ "response_type": "code",
85
+ "client_id": _setting("DSM_OAUTH_CLIENT_ID"),
86
+ "redirect_uri": _callback_uri(),
87
+ "scope": getattr(settings, "DSM_OAUTH_SCOPE", "profile"),
88
+ "state": state,
89
+ "code_challenge": _pkce_challenge(verifier),
90
+ "code_challenge_method": "S256",
91
+ }
92
+ authorize_url = getattr(
93
+ settings, "DSM_OAUTH_AUTHORIZE_URL", _provider_url("/o/authorize/")
94
+ )
95
+ return redirect(f"{authorize_url}?{urlencode(params)}")
96
+
97
+
98
+ @require_GET
99
+ def callback(request: HttpRequest) -> HttpResponse:
100
+ if request.GET.get("error"):
101
+ return JsonResponse({"error": "oauth_denied"}, status=403)
102
+
103
+ state = request.GET.get("state", "")
104
+ expected_state = request.session.pop("dsm_oauth_state", "")
105
+ verifier = request.session.pop("dsm_oauth_verifier", "")
106
+ code = request.GET.get("code", "")
107
+ if not state or not expected_state or not secrets.compare_digest(state, expected_state):
108
+ return JsonResponse({"error": "invalid_state"}, status=400)
109
+ if not verifier or not code:
110
+ return JsonResponse({"error": "missing_code_or_verifier"}, status=400)
111
+
112
+ try:
113
+ token_response = requests.post(
114
+ _provider_url("/o/token/"),
115
+ auth=_client_auth(),
116
+ data={
117
+ "grant_type": "authorization_code",
118
+ "code": code,
119
+ "redirect_uri": _callback_uri(),
120
+ "code_verifier": verifier,
121
+ },
122
+ timeout=15,
123
+ verify=getattr(settings, "DSM_OAUTH_VERIFY_SSL", True),
124
+ )
125
+ token_response.raise_for_status()
126
+ tokens = token_response.json()
127
+ if not isinstance(tokens, dict) or not isinstance(
128
+ tokens.get("access_token"), str
129
+ ):
130
+ return JsonResponse({"error": "invalid_token_response"}, status=502)
131
+ account_response = requests.get(
132
+ _provider_url("/api/account/"),
133
+ headers={"Authorization": f"Bearer {tokens['access_token']}"},
134
+ timeout=15,
135
+ verify=getattr(settings, "DSM_OAUTH_VERIFY_SSL", True),
136
+ )
137
+ account_response.raise_for_status()
138
+ account = account_response.json()
139
+ except (requests.RequestException, KeyError, ValueError):
140
+ return JsonResponse({"error": "oauth_exchange_failed"}, status=502)
141
+
142
+ if not isinstance(account, dict):
143
+ return JsonResponse({"error": "invalid_account"}, status=502)
144
+ subject = str(account.get("sub") or account.get("id") or "").strip()
145
+ try:
146
+ claims = verify_access_token(tokens["access_token"], expected_subject=subject)
147
+ except (jwt.PyJWTError, jwt.PyJWKClientError):
148
+ return JsonResponse({"error": "invalid_access_token"}, status=502)
149
+ if any(
150
+ claims[name] != bool(account.get(name))
151
+ for name in ("is_active", "is_staff", "is_superuser")
152
+ ):
153
+ return JsonResponse({"error": "account_token_mismatch"}, status=502)
154
+ user = sync_oauth_user(account)
155
+ if user is None:
156
+ return JsonResponse({"error": "invalid_account"}, status=502)
157
+ if not user.is_active or not user.is_staff:
158
+ return JsonResponse({"error": "admin_access_denied"}, status=403)
159
+
160
+ django_login(request, user, backend="django.contrib.auth.backends.ModelBackend")
161
+ request.session["dsm_oauth_access_token"] = tokens["access_token"]
162
+ refresh_token = tokens.get("refresh_token", "")
163
+ request.session["dsm_oauth_refresh_token"] = (
164
+ refresh_token if isinstance(refresh_token, str) else ""
165
+ )
166
+ request.session["dsm_oauth_account"] = account
167
+ return redirect(request.session.pop("dsm_oauth_next", "/admin/"))
168
+
169
+
170
+ @require_GET
171
+ def logout(request: HttpRequest) -> HttpResponse:
172
+ access_token = request.session.get("dsm_oauth_access_token")
173
+ refresh_token = request.session.get("dsm_oauth_refresh_token")
174
+ for token, hint in (
175
+ (refresh_token, "refresh_token"),
176
+ (access_token, "access_token"),
177
+ ):
178
+ if token:
179
+ try:
180
+ requests.post(
181
+ _provider_url("/o/revoke_token/"),
182
+ auth=_client_auth(),
183
+ data={"token": token, "token_type_hint": hint},
184
+ timeout=10,
185
+ verify=getattr(settings, "DSM_OAUTH_VERIFY_SSL", True),
186
+ )
187
+ except requests.RequestException:
188
+ pass
189
+ django_logout(request)
190
+ request.session.flush()
191
+ next_url = getattr(settings, "DSM_OAUTH_LOGOUT_REDIRECT_URL", "/admin/login/")
192
+ safe_next_url = _safe_next(request, next_url)
193
+ provider_logout = getattr(settings, "DSM_OAUTH_LOGOUT_URL", _provider_url("/logout/"))
194
+ return redirect(
195
+ f"{provider_logout}?{urlencode({'next': request.build_absolute_uri(safe_next_url)})}"
196
+ )
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: dsm-oauth-admin-client
3
+ Version: 0.1.0
4
+ Summary: Django client integration for DSM OAuth and Django Admin
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: Django>=4.2
8
+ Requires-Dist: PyJWT[crypto]<3,>=2.8
9
+ Requires-Dist: requests>=2.32.3
10
+
11
+ # DSM OAuth Admin Client
12
+
13
+ Installable Django app that simulates a relying client for this repository's DSM OAuth provider. It adds Authorization Code + PKCE login and Django Admin session creation.
14
+
15
+ ## Install from this repository
16
+
17
+ ```sh
18
+ pip install ./packages/dsm-oauth-admin-client
19
+ ```
20
+
21
+ ## Configure a Django client
22
+
23
+ Register a confidential OAuth application in DSM OAuth. Set its redirect URI to `https://client.example.test/oauth-admin/callback/` and grant the `profile` scope.
24
+
25
+ Add the app before `django.contrib.admin` so its admin login template takes precedence:
26
+
27
+ ```python
28
+ INSTALLED_APPS = [
29
+ "dsm_oauth_admin_client",
30
+ "django.contrib.admin",
31
+ # ...
32
+ ]
33
+
34
+ DSM_OAUTH_SERVER_URL = "https://oauth.example.test"
35
+ DSM_OAUTH_ISSUER = "https://oauth.example.test" # Set when issuer differs from server URL.
36
+ DSM_OAUTH_CLIENT_ID = "client-id"
37
+ DSM_OAUTH_CLIENT_SECRET = "read-from-environment"
38
+ DSM_OAUTH_CALLBACK_URL = "https://client.example.test/oauth-admin/callback/"
39
+ DSM_OAUTH_VERIFY_SSL = True
40
+ ```
41
+
42
+ Include the client routes:
43
+
44
+ ```python
45
+ from django.urls import include, path
46
+
47
+ urlpatterns = [
48
+ path("oauth-admin/", include("dsm_oauth_admin_client.urls")),
49
+ path("admin/", admin.site.urls),
50
+ ]
51
+ ```
52
+
53
+ To refresh tokens and synchronize staff access on authenticated requests, add the middleware after Django's `AuthenticationMiddleware`:
54
+
55
+ ```python
56
+ MIDDLEWARE = [
57
+ # ...
58
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
59
+ "dsm_oauth_admin_client.middleware.OAuthSessionValidationMiddleware",
60
+ # ...
61
+ ]
62
+ ```
63
+
64
+ The package keeps OAuth tokens in the Django session and maps provider profile fields `id`/`sub`, `username`, `email`, `first_name`, `last_name`, `is_active`, `is_staff`, and `is_superuser` to the local user. Only active staff users can enter Admin.
65
+
66
+ The callback fetches `/api/account/` once to create the local Django user. The middleware then verifies access-token signatures locally using the provider's `/api/access-token-jwks/` endpoint, refreshes expired tokens through `/o/token/`, and applies staff flags from verified token claims. It does not call the provider on every request. Role changes and token revocation are observed when the access token refreshes, so the delay can be up to the access-token lifetime. Logout attempts to revoke access and refresh tokens, clears the local Django session, then redirects through provider `/logout/`. If the provider is unavailable, local logout still completes; server-side tokens remain until revoked or expired.
67
+
68
+ Account linking uses the provider's stable `sub` (or `id`) plus issuer URL, not the mutable username. Existing local users are not linked by matching username; a separate local account is created if that username is already taken. Run `python manage.py migrate` after installing the app.
69
+
70
+ Set `DSM_OAUTH_ISSUER` to the exact token issuer if it differs from `DSM_OAUTH_SERVER_URL`. Set `DSM_OAUTH_JWKS_URL` only when the provider's access-token JWKS endpoint uses a custom URL.
71
+
72
+ Do not expose the client secret to browser code. Use HTTPS and a protected Django session backend in production.
73
+ The package rejects Django's signed-cookie session backend because browser-readable cookies would contain OAuth tokens. On HTTPS deployments, set `SESSION_COOKIE_SECURE = True`, `SESSION_COOKIE_HTTPONLY = True`, `CSRF_COOKIE_SECURE = True`, and `SESSION_COOKIE_SAMESITE = "Lax"`.
@@ -0,0 +1,20 @@
1
+ README.md
2
+ pyproject.toml
3
+ dsm_oauth_admin_client/__init__.py
4
+ dsm_oauth_admin_client/apps.py
5
+ dsm_oauth_admin_client/auth.py
6
+ dsm_oauth_admin_client/middleware.py
7
+ dsm_oauth_admin_client/models.py
8
+ dsm_oauth_admin_client/services.py
9
+ dsm_oauth_admin_client/tests.py
10
+ dsm_oauth_admin_client/token_validation.py
11
+ dsm_oauth_admin_client/urls.py
12
+ dsm_oauth_admin_client/views.py
13
+ dsm_oauth_admin_client.egg-info/PKG-INFO
14
+ dsm_oauth_admin_client.egg-info/SOURCES.txt
15
+ dsm_oauth_admin_client.egg-info/dependency_links.txt
16
+ dsm_oauth_admin_client.egg-info/requires.txt
17
+ dsm_oauth_admin_client.egg-info/top_level.txt
18
+ dsm_oauth_admin_client/migrations/0001_initial.py
19
+ dsm_oauth_admin_client/migrations/__init__.py
20
+ dsm_oauth_admin_client/templates/admin/login.html
@@ -0,0 +1,3 @@
1
+ Django>=4.2
2
+ PyJWT[crypto]<3,>=2.8
3
+ requests>=2.32.3
@@ -0,0 +1 @@
1
+ dsm_oauth_admin_client
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=75"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dsm-oauth-admin-client"
7
+ version = "0.1.0"
8
+ description = "Django client integration for DSM OAuth and Django Admin"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "Django>=4.2",
13
+ "PyJWT[crypto]>=2.8,<3",
14
+ "requests>=2.32.3",
15
+ ]
16
+
17
+ [tool.setuptools.packages.find]
18
+ where = ["."]
19
+ include = ["dsm_oauth_admin_client*"]
20
+
21
+ [tool.setuptools.package-data]
22
+ dsm_oauth_admin_client = ["templates/admin/*.html"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+