diff --git a/docs/openapi.rst b/docs/openapi.rst index 9e32c5b4..df350d69 100644 --- a/docs/openapi.rst +++ b/docs/openapi.rst @@ -149,6 +149,37 @@ Documentation components can be passed by accessing the internal apispec {'description': 'Item ID', 'format': 'int32', 'required': True} ) +Use Swagger OAuth2 Authentication +--------------------------------- + +Swagger can automatically redirect to OAuth2 URLs and retrieve a token for use as an Authentication Header. See the `Swagger OAuth2 Docs`_ for more information. Your redirect to supply to your OAuth provider will be ``{HOST}://{OPENAPI_URL_PREFIX}/{OPENAPI_SWAGGER_UI_PATH}/oauth2-redirect``. The code below is an example of what should be supplied as config to app in order to activate this feature. + +.. code-block:: python + + app.config['API_SPEC_OPTIONS'] = {'components': + { + 'securitySchemes': { + }, + 'OAuth2': { + 'type': 'oauth2', + 'flows': { + 'implicit': { + 'authorizationUrl': self.AUTHORIZATION_URL, + 'scopes': { + 'openid': 'openid token' + } + } + } + } + } + }, + 'security': [{ + 'OAuth2': [] + }] + } + app.config['OPENAPI_SWAGGER_UI_ENABLE_OAUTH'] = True + + Register Custom Fields ---------------------- @@ -276,3 +307,4 @@ number. .. _ReDoc: https://github.com/Rebilly/ReDoc .. _Swagger UI: https://swagger.io/tools/swagger-ui/ +.. _Swagger OAuth2 Docs: https://swagger.io/docs/specification/authentication/oauth2/ diff --git a/flask_rest_api/spec/__init__.py b/flask_rest_api/spec/__init__.py index 8f4a5a9d..de2a2165 100644 --- a/flask_rest_api/spec/__init__.py +++ b/flask_rest_api/spec/__init__.py @@ -123,6 +123,16 @@ def _register_swagger_ui_rule(self, blueprint): _add_leading_slash(swagger_ui_path), endpoint='openapi_swagger_ui', view_func=self._openapi_swagger_ui) + if (self._app.config.get( + 'OPENAPI_SWAGGER_UI_ENABLE_OAUTH', False)): + blueprint.add_url_rule( + _add_leading_slash( + '{}/oauth2-redirect'.format( + swagger_ui_path + ) + ), + endpoint='openapi_swagger_ui_redirect', + view_func=self._openapi_swagger_ui_redirect) def _openapi_json(self): """Serve JSON spec file""" @@ -142,10 +152,18 @@ def _openapi_swagger_ui(self): return flask.render_template( 'swagger_ui.html', title=self._app.name, swagger_ui_url=self._swagger_ui_url, + swagger_ui_enable_oauth=self._app.config.get( + 'OPENAPI_SWAGGER_UI_ENABLE_OAUTH', False), swagger_ui_supported_submit_methods=( self._swagger_ui_supported_submit_methods) ) + def _openapi_swagger_ui_redirect(self): + """Expose OpenAPI redirect url with Swagger UI""" + return flask.render_template( + 'swagger_ui_redirect.html' + ) + class APISpecMixin(DocBlueprintMixin): """Add APISpec related features to Api class""" diff --git a/flask_rest_api/spec/templates/swagger_ui.html b/flask_rest_api/spec/templates/swagger_ui.html index 06ed47a8..e8f5ec62 100644 --- a/flask_rest_api/spec/templates/swagger_ui.html +++ b/flask_rest_api/spec/templates/swagger_ui.html @@ -15,6 +15,9 @@ \ No newline at end of file