Django REST Swagger: how to use the security section in Swagger settings?

I am trying to create Swagger settings for SecurityDefinition to get the following result in openapi.json:

"securityDefinitions": { "password": { "type": "oauth2", "tokenUrl": "http://example.com/oauth/token", "flow": "password", "scopes": { "write": "allows modifying resources", "read": "allows reading resources" } } }, "security": [{ "password": ["read", "write"] }] 

In my settings.py, I added the following swagger options:

 # Swagger settings SWAGGER_SETTINGS = { "SECURITY_DEFINITIONS": { "password": { "type": "oauth2", "tokenUrl": "http://example.com/oauth/token", "flow": "password", "scopes": { "write": "allows modifying resources", "read": "allows reading resources" } } }, "SECURITY": [{ "password": ["read", "write"] }] } 

The problem is that openapi.json, which is generated by Swagger, does not have a security dict, and I do not know how it is generated.

Below is the generated openapi.json file:

 { "info": { "title": "Example Service API", "version": "" }, "host": "http://example.com", "swagger": "2.0", "securityDefinitions": { "password": { "type": "oauth2", "scopes": { "write": "allows modifying resources", "read": "allows reading resources" }, "tokenUrl": "http://example.com/oauth/token", "flow": "password" } }, "paths": {...} } 

Is there a better way to describe this concept in my Swagger settings? Or can you describe me what process and how it works to generate openapi.json file?

+6
source share
1 answer

If in doubt, check the code. You can see the definition of OpenAPIRenderer here :

 class OpenAPIRenderer(BaseRenderer): media_type = 'application/openapi+json' charset = None format = 'openapi' def render(self, data, accepted_media_type=None, renderer_context=None): if renderer_context['response'].status_code != status.HTTP_200_OK: return JSONRenderer().render(data) extra = self.get_customizations() return OpenAPICodec().encode(data, extra=extra) def get_customizations(self): """ Adds settings, overrides, etc. to the specification. """ data = {} if swagger_settings.SECURITY_DEFINITIONS: data['securityDefinitions'] = swagger_settings.SECURITY_DEFINITIONS return data 

Thus, one way to do this is to subclass, for example:

 class MyOpenAPIRenderer(OpenAPIRenderer): def get_customizations(self): data = super().get_customizations() # your customizations data["security"] = swagger_settings.SECURITY return data 

Then you can use this visualization class for your view. Hope this helps!

+3
source

Source: https://habr.com/ru/post/1014249/


All Articles