Secure Headers for Python Web Frameworks
Secure is a lightweight Python library designed to effortlessly add essential HTTP security headers to web applications. It supports multiple frameworks like Flask, FastAPI, and Django with a unified, modern API. The library is actively maintained, with the current stable version being 1.0.1, and a 2.0.0 release candidate introducing significant enhancements and API changes.
Warnings
- breaking Version 2.0.0 (currently in Release Candidate) introduces a significant API overhaul, including a new preset model (e.g., `Preset.BALANCED`), first-class ASGI/WSGI middleware, and changes to the behavior of `with_default_headers()`. Review the migration guide when upgrading to 2.x.x.
- breaking The library underwent a complete API redesign in v1.0.0 from its 0.x.x versions. Old classes like `SecureHeaders` and `SecureCookie` were removed or replaced. Additionally, v1.0.0 requires Python 3.10+.
- breaking The `SecureCookie` class and all cookie management features were removed starting from version 0.3.0 and are not present in 1.x.x or 2.x.x. The library now exclusively focuses on HTTP security headers.
- gotcha The `Feature-Policy` HTTP header was renamed to `Permissions-Policy` as part of a specification update. `secure.py` adopted this change in v0.3.0/v1.0.0, so older configurations might be using the deprecated name.
Install
-
pip install secure
Imports
- Secure
from secure import Secure
- ContentSecurityPolicy
from secure import ContentSecurityPolicy
- PermissionsPolicy
from secure import PermissionsPolicy
- SecureWSGIMiddleware
from secure.middleware import SecureWSGIMiddleware
- SecureASGIMiddleware
from secure.middleware import SecureASGIMiddleware
- SecureHeaders
from secure import Secure
- SecureCookie
N/A (Functionality removed)
Quickstart
import os
from flask import Flask, Response
from secure import Secure
app = Flask(__name__)
# Instantiate Secure with default headers (or customize)
# For v2.0.0rc1 and later, consider `Secure.with_preset(Preset.BALANCED)` or middleware.
secure_headers = Secure.with_default_headers()
@app.after_request
def add_security_headers(response: Response):
secure_headers.set_headers(response)
return response
@app.route("/")
def home():
return "Hello, secure world!"
if __name__ == "__main__":
# In a real application, use a production-ready WSGI server like Gunicorn
app.run(debug=True)