Skip to content

Class swarmauri_middleware_securityheaders.SecurityHeadersMiddleware.SecurityHeadersMiddleware

swarmauri_middleware_securityheaders.SecurityHeadersMiddleware.SecurityHeadersMiddleware

SecurityHeadersMiddleware(app)

Bases: Middleware

Middleware that adds secure HTTP headers to responses.

This middleware adds various security headers to responses to help protect against common web vulnerabilities. The headers implemented include Content-Security-Policy, X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, Strict-Transport-Security, Referrer-Policy, and Permissions-Policy.

ATTRIBUTE DESCRIPTION
app

The ASGI application instance

Source code in swarmauri_middleware_securityheaders/SecurityHeadersMiddleware.py
23
24
25
26
27
def __init__(
    self, app: Callable[[Request, Callable[[Request], Response]], Response]
):
    super().__init__(app)
    self.app = app

app instance-attribute

app = app

dispatch async

dispatch(request, call_next)

Dispatches the request and adds security headers to the response.

This method is responsible for adding security headers to the response before sending it back to the client. It does this by calling the next middleware in the chain and then modifying the response headers.

PARAMETER DESCRIPTION
request

The incoming request object

TYPE: Request

call_next

A callable that invokes the next middleware in the chain

TYPE: Callable[[Request], Response]

RETURNS DESCRIPTION
Response

The response object with added security headers

Source code in swarmauri_middleware_securityheaders/SecurityHeadersMiddleware.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
async def dispatch(
    self, request: Request, call_next: Callable[[Request], Response]
) -> Response:
    """Dispatches the request and adds security headers to the response.

    This method is responsible for adding security headers to the response
    before sending it back to the client. It does this by calling the
    next middleware in the chain and then modifying the response
    headers.

    Args:
        request: The incoming request object
        call_next: A callable that invokes the next middleware
            in the chain

    Returns:
        The response object with added security headers
    """
    response = await call_next(request)

    if isinstance(response, Response):
        # Add security headers
        self._add_security_headers(response)

    return response