Reputation: 387
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
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
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:
oauth2_provider
(as you did)OAuth2Authentication
and the corresponding permission_classes
(directly or via DRF default setting)Upvotes: 1