Home > front end >  Django DRF How to force login on swagger
Django DRF How to force login on swagger

Time:07-11

I'm using Django Rest Framework in a project with swagger for documentation.

Swagger UI can be accessed by everyone who knows its URL. Is that possible to add an authentication method so only people with the right access can see and read swagger docs?

on urls.py

schema_view = get_schema_view(
    openapi.Info(
        title="API Docs",
        default_version='v1',
        description="beautiful and long text",
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
)

...

urlpatterns = [
    url(
        r'^swagger/$',
        schema_view.with_ui('swagger', cache_timeout=0),
        name='schema-swagger-ui'
    ),
    url(
        r'^redoc/$',
        schema_view.with_ui('redoc', cache_timeout=0),
        name='schema-redoc'
    ),
]

on settings.py

SWAGGER_SETTINGS = {
    'SHOW_REQUEST_HEADERS': True,
    'SECURITY_DEFINITIONS': {
        'Bearer': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header',
        },
        'basic': {
            'type': 'basic'
        }
    },
    'USE_SESSION_AUTH': True,
    'JSON_EDITOR': True,
    'SUPPORTED_SUBMIT_METHODS': [
        'get',
        'post',
        'put',
        'delete',
        'patch'
    ],
}

CodePudding user response:

You want permission_required('myspecpermission',login_url="../mylogintouseswagger") More about it: https://docs.djangoproject.com/en/4.0/topics/auth/default/#the-permission-required-decorator

You should add in your urls.py:

urls.py

from django.contrib.auth.decorators import permission_required
...

urlpatterns = [
    url(
        r'^swagger/$',
        permission_required('MySpecPermissionForSwagger',login_url="../mylogintouseswagger")(schema_view.with_ui('swagger', cache_timeout=0)),
        name='schema-swagger-ui'
    ),
    url(
        r'^redoc/$',
        permission_required('MySpecPermissionForRedoc',login_url="../mylogintousesredoc")(schema_view.with_ui('redoc', cache_timeout=0)),
        name='schema-redoc'
    ),
]

MySpecPermissionForSwagger - this is name of the the custom permission from django permissiions. More about it: https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#custom-permissions

  • Related