Skip to content

Commit 540d7d6

Browse files
authored
Merge pull request #417 from gabriels1234/feat/django-csp-4-compat
Add django-csp v4.0 compatibility
2 parents 8cefd5f + f1f8df6 commit 540d7d6

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

djangosaml2/utils.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import zlib
1919
from functools import lru_cache, wraps
2020
from typing import Optional
21+
from importlib.metadata import version, PackageNotFoundError
2122

2223
from django.conf import settings
2324
from django.core.exceptions import ImproperlyConfigured
@@ -239,6 +240,7 @@ def _django_csp_update_decorator():
239240
"""Returns a view CSP decorator if django-csp is available, otherwise None."""
240241
try:
241242
from csp.decorators import csp_update
243+
import csp
242244
except ModuleNotFoundError:
243245
# If csp is not installed, do not update fields as Content-Security-Policy
244246
# is not used
@@ -254,4 +256,26 @@ def _django_csp_update_decorator():
254256
else:
255257
# autosubmit of forms uses nonce per default
256258
# form-action https: to send data to IdPs
257-
return csp_update(FORM_ACTION=["https:"])
259+
# Check django-csp version to determine the appropriate format
260+
try:
261+
csp_version = version('django-csp')
262+
major_version = int(csp_version.split('.')[0])
263+
264+
# Version detection successful
265+
if major_version >= 4:
266+
# django-csp 4.0+ uses dict format with named 'config' parameter
267+
return csp_update(config={"form-action": ["https:"]})
268+
# django-csp < 4.0 uses kwargs format
269+
return csp_update(FORM_ACTION=["https:"])
270+
except (PackageNotFoundError, ValueError, RuntimeError, AttributeError, IndexError):
271+
# Version detection failed, we need to try both formats
272+
# Try v4.0+ style first because:
273+
# 1. It has better error handling with clear messages
274+
# 2. Newer versions are more likely to be supported in the future
275+
# 3. If using kwargs with v4.0, it raises a specific RuntimeError we can catch
276+
try:
277+
return csp_update(config={"form-action": ["https:"]})
278+
except (TypeError, RuntimeError):
279+
# TypeErrors could happen if config is not a recognized parameter (v3.x)
280+
# RuntimeErrors could happen in v4.0+ if we try the wrong approach
281+
return csp_update(FORM_ACTION=["https:"])

0 commit comments

Comments
 (0)