简体   繁体   中英

How can I configure "HTTPS" schemes with the drf-yasg auto-generated swagger page?

I know in a traditional swagger YAML file, we can define the schemes with:

schemes:
  - http
  - https

//OR

schemes: [http, https]

However, how can I do the same thing with auto-generated swagger page with the drf-yasg library?

Now, the generated swagger page only contains HTTP schemes, but HTTPS is missing. I've tried set the DEFAULT_API_URL in setting.py to https://mybaseurl.com , but it seems not to be working.

There is a solution.

When defining get_schema_view() in urls.py , use this code:

schema_view = get_schema_view(
    openapi.Info( ... ),
    url='https://example.net/api/v1/', # Important bit
    public=True,
    permission_classes=(permissions.AllowAny,)
)

Note: You can either use https or http because of that better use this solution with an environment variable for different setups.

To use both http and https schemes in swagger you can extend OpenAPISchemaGenerator from drf_yasg.generators .

class BothHttpAndHttpsSchemaGenerator(OpenAPISchemaGenerator):
    def get_schema(self, request=None, public=False):
        schema = super().get_schema(request, public)
        schema.schemes = ["http", "https"]
        return schema

So now you can use it as generator_class for get_schema_view()

schema_view = get_schema_view(
    openapi.Info( ... ),
    public=True,
    generator_class=BothHttpAndHttpsSchemaGenerator, # Here
    permission_classes=(AllowAny,)
)

Put

url='https://your_server_address/'

in the get_schema_view() function with a URL.

Another way to have https scheme in swagger page is to use SECURE_PROXY_SSL_HEADER configuration.

Assuming that your Django REST API is sitting behind an Nginx that is doing SSL termination, you can let the Nginx forward X-Forwarded-Proto: https to your Django application (Nginx might already forward this header by default depending on how you set things up). With the configuration below, your Django application will realize that it is behind a SSL terminating Nginx, and Django's internal function is_secure() will return True when the header is present. Refer to Django SSL Settings .

Once the is_secure() returns True , the swagger page scheme will automatically turn into https .

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

I like this approach since it does not require any hard coding url or even configuring url from environment variables. Additionally, the is_secure() function is used internally in other place as well so it is desirable to have the function work as it idealy should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM