secure
secure copied to clipboard
starlette `middleware` decorator is deprecated
The example code for starlette proposes to use the middleware decorator: https://secure.readthedocs.io/en/latest/frameworks.html#starlette
Anyhow, this decorator is deprecated, and will be removed in version 1.0.0 - at least there is a warning about that.
The message is:
[...]/site-packages/starlette/applications.py:248: DeprecationWarning: The `middleware` decorator is deprecated, and will be removed in version 1.0.0. Refer to https://www.starlette.io/middleware/#using-middleware for recommended approach.
It would be good to update the help.
I'm using this now, but would not say that I'm confident this is the correct solution:
class SecureHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
secure_headers.framework.starlette(response)
return response
app.add_middleware(SecureHeadersMiddleware)
Thank you @fnep! I’ll test and adjust the documentation.
@cak My code from above is probably not the best for an example. There are other issues with it that i discovered later.
Im using this now:
class SecurityHeadersMiddleware:
"""Middleware to add security headers to the response."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
return await self.app(scope, receive, send)
async def send_with_security_headers(message: Message) -> None:
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
for key, value in secure_headers.headers_tuple():
headers.append(key, value)
await send(message)
await self.app(scope, receive, send_with_security_headers)