gigahex
gigahex

Reputation: 387

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?

Upvotes: 0

Views: 1404

Answers (2)

gigahex
gigahex

Reputation: 387

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)

Upvotes: 3

Insa
Insa

Reputation: 1861

The oauth toolkit does provides regular html views, which are not DRF views. Therefore they do not appear in the schema because spectacular can only parse any of the DRF-type views.

What you need to do is add some settings that direct SwaggerUI to those auth views:

SPECTACULAR_SETTINGS = {
    # Oauth2 related settings. used for example by django-oauth2-toolkit.
    # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#oauth-flows-object
    'OAUTH2_FLOWS': [],
    'OAUTH2_AUTHORIZATION_URL': None,
    'OAUTH2_TOKEN_URL': None,
    'OAUTH2_REFRESH_URL': None,
    'OAUTH2_SCOPES': None,
    # other spectcular settings
}

So 3 steps are basically required to make this fully functional:

  • Add the views to urlpatterns for oauth2_provider (as you did)
  • Make sure the views have OAuth2Authentication and the corresponding permission_classes (directly or via DRF default setting)
  • Add the settings as outlined above. You may not need all of them depending on the supported flows you have to set at least some URLs there.

Upvotes: 1

Related Questions