I'm digging google for 3 hours right now, and can't find solution for my problem. I moved in my project from drf-yasg to drf-spectacular because openapi +3.0 isn't supported in yasg. I want to have an authentication to swagger page. I had a solution like this for yasg:
schema_view = get_schema_view(
openapi.Info(
title="API",
default_version="v2",
description="api description",
terms_of_service="",
contact=openapi.Contact(email=""),
license=openapi.License(name=""),
),
public=True,
patterns=swagger_urls,
authentication_classes=(isStaffPermission,),
)
The problem is I can't add a similar solution to drf-spectacular. Right now I have this piece of code which ofc doesn't work. My goal is to run a popup for login before swagger page is rendered:
class MySchemaView(SpectacularAPIView):
urlconf=swagger_urls
class CustomSpectacularSwaggerView(SpectacularSwaggerView):
authentication_classes=(isStaffPermission,)
urlpatterns += [
path("api/v3/schema/", MySchemaView.as_view(api_version="v3"), name="schema"),
path('api/v3/swagger-ui/', CustomSpectacularSwaggerView.as_view(), name='swagger-ui')
]
I want to authenticate with my custom class:
class isStaffPermission(authentication.BasicAuthentication):
"""Custom authentication class to check if the user is staff."""
def authenticate(self, request) -> Optional[User]:
"""Authenticate the user"""
user: Optional[User, bool] = super().authenticate(request)
if user and user[0] and user[0].is_staff:
return user
return None
Does anyone know how to fix it?
Authentication & permissions
You can set the required authentication and permissions via settings
SPECTACULAR_DEFAULTS = {
...
# list of authentication/permission classes for spectacular's views.
'SERVE_PERMISSIONS': ['rest_framework.permissions.AllowAny'],
# None will default to DRF's AUTHENTICATION_CLASSES
'SERVE_AUTHENTICATION': None,
}
Docs: https://drf-spectacular.readthedocs.io/en/latest/settings.html
Popup
If you want to display a login popup, the simplest solution would be to render a custom view under api/v3/swagger-ui/, with the logic to check if user is already authenticated.
If yes, redirect him to the actual Swagger UI, if not, show him the login page/popup -> perform authentication -> redirect to Swagger UI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With