[Django]-How to add password and username pop up for Django Swagger?

2👍

To have the popup for authentication in ‘DRF’ and also in ‘SWAGGER’ panel, simply add these lines of code which I arrowed to your settings.py:

‘DRF’ implementation



REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # the link you can read about
        # https://stackoverflow.com/questions/51906745/django-rest-framework-logout-not-working-after-token-authentication

        'rest_framework.authentication.BasicAuthentication', # <<--

        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

In REST_FRAMEWORK, inside the DEFAULT_AUTHENTICATION_CLASSES, (which is a list) add the
rest_framework.authentication.BasicAuthentication.
It tells the djagno to authenticate using the default authentication that djagno provides.

‘SWAGGER’ implementation

If you want to use it in ‘SWAGGER’ as well, do the below:

In SWAGGER_SETTINGS, inside the SECURITY_DEFINITIONS which is a dict, add these lines of code to implement that:

'basic': {
    'type': 'basic'
},

Default ‘swagger’ settings would be like this:

SWAGGER_SETTINGS = {
    'DOC_EXPANSION': 'list',
    'APIS_SORTER': 'alpha',
    'USE_SESSION_AUTH': False,
    'SECURITY_DEFINITIONS': {
        'Bearer': {  # <<-- is for JWT access token
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header'
        },
        'basic': {  # <<-- is for djagno authentication 
            'type': 'basic'
        },
    },
}

Attention that Bearer is for JWT access token. basic is for djagno authentication.

Thant you for reading!

Leave a comment