tfranzel / drf-spectacular

Sane and flexible OpenAPI 3 schema generation for Django REST framework.
https://drf-spectacular.readthedocs.io
BSD 3-Clause "New" or "Revised" License
2.36k stars 262 forks source link

[Question] Does `{% if user.is_authenticated %}` not work with swagger_ui.html? #935

Closed alokshenoy closed 1 year ago

alokshenoy commented 1 year ago

I'm currently overriding the default templates for swagger UI to include a navigation bar at the top. Since the api docs are secured by login using the following:

path(
        "api/docs/",
        login_required(SpectacularSwaggerView.as_view(url_name="schema")),
        name="api/docs",
    ),

my swagger_ui.html uses {% if user.is_authenticated %} <show a> {% else %} <show b> {% endif %} quite liberally, and I invariably see b instead of a.

tfranzel commented 1 year ago

Well I don't think this has anything to do with spectacular. What is the used authentication method? If you simply direct your browser there, I think nothing will work except for the automatic CookieAuthentication. Sounds logical that you then don't have authentication in the template or the view for that matter. Also, SpectacularSwaggerView will use your default auth method unless otherwise configured.

If you use the authentication button in SwaggerUI, that is a different story. We go the extra mile to re-request the schema with that auth, but that does not apply to the SwaggerUI endpoint itself.

fyi: swagger has a built-in topbar for different schema urls. e.g.:

SPECTACULAR_SETTINGS = {
    "SWAGGER_UI_SETTINGS": """{
        deepLinking: true,
        displayOperationId: true,
        persistAuthorization: true,
        urls: [{url: "/api/schema/?version=v1", name: "version 1"}],
        presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
        layout: "StandaloneLayout",
    }""",
}
alokshenoy commented 1 year ago

ah! that makes sense. I had to update the auth classes to :

    "DEFAULT_AUTHENTICATION_CLASSES": [
        "knox.auth.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ],