Search code examples
django-rest-frameworkswaggerswagger-uidrf-yasgdrf-spectacular

Django drf-spectacular with FirebaseBackend auth


To give as much context as possible; I have two problems while using drf-spectacular to build my API documentation;

  1. With my default configuration, I cannot even load the documentation's page because I have a custom auth backend (using firebase_admin 5.2.0), the swagger (or ReDoc) are part of my REST API, therefore, would have to pass a valid token to load the page allocated in the documentation's endpoint (which is not possible from a browser).

  2. Second, and most importantly, I am not able to configure my custom firebase auth with drf-spectacular to implement a Swagger authentication method to execute against my API endpoints. I would be just fine having the possibility to add a token in the Swagger doc, do not need to have all Firebase auth credentials, URLs, and flow.

  • api/urls.py
router = routers.DefaultRouter()

urlpatterns = [
    path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
    path('api/schema/swagger/', SpectacularSwaggerView.as_view(), name='swagger'),
    path('api/schema/redoc/', SpectacularRedocView.as_view(), name='redoc'),

    # _____________________FIREBASE AUTH ______________________

    path('api-auth/', include('rest_framework.urls')),
    path('', include(router.urls)),

  • settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'auth.backends.FirebaseBackend',
    ],
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

I have unsuccessfully tried adding many different configurations to my SPECTACULAR_SETTINGS.

Thanks in advance!!


Solution

    1. By default spectacular uses 'SERVE_PERMISSIONS': ['rest_framework.permissions.AllowAny'], which should allow opening the swagger page even if not authenticated. Maybe FirebaseBackend bails hard which prevents you ever getting to AllowAny. Try this to take Firebase out of the equation for the schema views:
    SPECTACULAR_SETTINGS = {
        ...
        'SERVE_PERMISSIONS': ['rest_framework.permissions.AllowAny']
        'SERVE_AUTHENTICATION': [],
    }
    
    1. You need to write an OpenApiAuthenticationExtension for Firebase as it is not part of the spectacular at the moment.