10

I'm using drf_yasg for swagger documentation. When I publish my DRF app behind AWS Application Load Balancer and set listener to listen on 443 HTTPS and redirect to my EC2 on which DRF is running, swagger UI is trying to send a request to endpoint http://example.com/status rather than e.g. https://example.com/status. This creates a Google Chrome error:

swagger-ui-bundle.js:71 Mixed Content: The page at 'https://example.com/swagger#/status/status_list' was loaded over HTTPS, but requested an insecure resource 'http://example.com/status'. This request has been blocked; the content must be served over HTTPS.

So my solution to solve this was to explicitly set my server URL in drf_yasg.views.get_schema_view. So my code looks like:

schema_view = get_schema_view(
    openapi.Info(
        title="Server Api Documentation",
        default_version="v1",
        description="",
    url="http://example.com/status"
)

# noinspection PyUnresolvedReferences
swagger_patterns = [
    path("", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"),

I would like to be able not to explicitly set URL string but rather choose Schemes between HTTP or HTTPS. Is it possible in drf_yasg?

2 Answers2

13

Add these in your Django settings.py

# Setup support for proxy headers
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Neelesh Batham
  • 156
  • 1
  • 4
6

If you are using nginx make sure proper header is set (X-Forwarded-Proto). Actually, check all nginx reverse proxy configs sitting between end-user and web server (gunicorn / uwsgi) like nginx on host machine and e.g. nginx deployed in docker.

location / {
    proxy_pass http://django:5000;
    proxy_set_header  Host              $http_host;
    proxy_set_header  X-Real-IP         $remote_addr;
    proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
    # check line below!
    proxy_set_header  X-Forwarded-Proto https;
    proxy_set_header  X-Forwarded-Referrer $http_referer;
    proxy_set_header  Referer $http_referer;
}
michal-michalak
  • 827
  • 10
  • 6