pythonpython-3.xdjango-rest-frameworkdjango-swaggerdrf-spectacular

How to include Oauth2 auth urls in Swagger?


I use Django drf-spectacular OAuth Toolkit for an Oauth2 password flow. Unfortunately, Swagger doesn't recognize the auth URLs. This is my urls.py

urlpatterns = [

# schema
path("api/schema/", SpectacularAPIView.as_view(api_version='v1'), name="schema"),
path(
    "api/schema/swagger/",
    SpectacularSwaggerView.as_view(url_name="schema"),
    name="swagger-ui",
),
path(
    "api/schema/redoc/",
    SpectacularRedocView.as_view(url_name="schema"),
    name="redoc",
),
path("api/oauth/", include("apps.main.oauth.urls", namespace="oauth2_provider")),
]

How can I fix thit?


Solution

  • To make it available to swagger you have to override the Oauth API, for example, override the token API and and write an inline serializer in the @extend_schema and pass the post method.

    from drf_spectacular.utils import extend_schema, inline_serializer
    from oauth2_provider.views.application import TokenView
    
    class TokenApiView(TokenView, APIView):
    
    @extend_schema(
        request=inline_serializer(
            name="InlineTokenSerializer",
            fields={
                "username": serializers.CharField(),
                "password": serializers.CharField(),
                "grant_type": serializers.CharField(required=False),
                "Scope": serializers.CharField(required=False),
                "client_id": serializers.CharField(),
            },
        )
    )
    def post(self, request, *args, **kwargs):
        return super().post(request, *args, **kwargs)