secure icon indicating copy to clipboard operation
secure copied to clipboard

starlette `middleware` decorator is deprecated

Open fnep opened this issue 2 years ago • 2 comments

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)

fnep avatar Aug 09 '23 10:08 fnep

Thank you @fnep! I’ll test and adjust the documentation.

cak avatar Apr 29 '24 11:04 cak

@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)

fnep avatar Apr 29 '24 12:04 fnep