Enabling https on a Uvicorn Python Application deployed to Azure

Published on

Heads up! This information might be outdated since it was last updated over a year ago. Please double-check the information before relying on it.

Like many services, Azure terminates SSL at the network load balancer. In plain English, your application needs to check the headers provided to it, to figure out if your user has connected via https.

If you’re using Uvicorn or another ASGI provider, you’ll need to include middleware, to check the X-Forwarded-Proto and X-Forwarded-For headers.

Thankfully, Uvicorn already provides a package you can import for this: uvicorn.middleware.proxy_headers.ProxyHeadersMiddleware.

Import the full uvicorn.middleware.proxy_headers.ProxyHeadersMiddleware package, specifying a specific trusted host to check for headers, or use a wildcard for all hosts.

For example, in a Starlette deployment you could include the library like so:

import uvicorn
# ...
        uvicorn.middleware.proxy_headers.ProxyHeadersMiddleware, trusted_hosts="*"
    )# Add the uvicorn middleware to the Starlette middleware classes
# ...