Django Permissions Policy
django-permissions-policy is a Django middleware that sets the Permissions-Policy HTTP header on your Django application. This header allows web developers to selectively enable or disable various browser features and APIs (e.g., camera, geolocation, autoplay) for the current document and any embedded iframes, enhancing security and privacy. The library, currently at version 4.29.0, is actively maintained with a regular release cadence.
Warnings
- breaking The library was renamed from `django-feature-policy` to `django-permissions-policy` in version 4.0.0. The middleware class was renamed from `FeaturePolicyMiddleware` to `PermissionsPolicyMiddleware`, and the setting from `FEATURE_POLICY` to `PERMISSIONS_POLICY`. While old names are supported as aliases for backward compatibility, it's recommended to update to the new names.
- gotcha When specifying origins in your policy settings (e.g., for `PERMISSIONS_POLICY`), use Python strings like `'self'`, `'*'`, or `'https://example.com'`. Do not include double quotes around domain names, as the middleware automatically adds them for the HTTP header. For example, use `'https://example.com'` instead of `"https://example.com"`.
- gotcha To entirely disallow a feature (no origins allowed), use an empty list `[]` as its value in the policy dictionary. The legacy value `'none'` is supported for backward compatibility but is ignored and should be replaced with `[]`.
- gotcha Incorrect keys or values in `PERMISSIONS_POLICY` or `PERMISSIONS_POLICY_REPORT_ONLY` settings can raise an `ImproperlyConfigured` exception. Browsers may also log warnings for features they don't recognize; these can generally be ignored if the names are valid according to the W3C spec, as the library performs basic validation.
- gotcha The placement of `PermissionsPolicyMiddleware` within your `MIDDLEWARE` list in `settings.py` is crucial. It's recommended to place it after `django.middleware.security.SecurityMiddleware` to ensure it integrates correctly within Django's security stack.
Install
-
pip install django-permissions-policy
Imports
- PermissionsPolicyMiddleware
from django_permissions_policy import PermissionsPolicyMiddleware
Quickstart
# settings.py
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"django_permissions_policy.PermissionsPolicyMiddleware",
# ...
]
PERMISSIONS_POLICY = {
"accelerometer": [],
"ambient-light-sensor": [],
"autoplay": [],
"camera": [],
"display-capture": [],
"encrypted-media": [],
"fullscreen": [],
"geolocation": [],
"gyroscope": [],
"interest-cohort": [],
"magnetometer": [],
"microphone": [],
"midi": [],
"payment": [],
"usb": [],
}
# Or for report-only mode:
# PERMISSIONS_POLICY_REPORT_ONLY = {
# "geolocation": ["self"],
# "camera": [],
# }