django-rest-swagger icon indicating copy to clipboard operation
django-rest-swagger copied to clipboard

Token Auth

Open gfrancqu opened this issue 6 years ago • 9 comments

Hi,

I'm having issue setting up the token authentication with django_rest_swagger, I'm actually using session authentication and token authentication

I successfully setup the token authentication in my app, but in the swagger view I'm facing two issues:

  • the POST api-auth-token endpoint have no inputs in the swagger view to enter the username and password
  • when I enter my token with the Authorize button I don't see my other endpoint (but with the login button which allow me to use session authentication it work well)

here are the versions I use

django-rest-swagger (2.1.2)
djangorestframework (3.7.1)
Python 3.6.2

my settings.py

# extending django users
AUTH_USER_MODEL = 'users.User'

#authentication
SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
}


# custom options for rest framework

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}
LOGIN_URL = 'rest_framework:login'
LOGOUT_URL = 'rest_framework:logout'

my urls.py


# this is a workaround i tried but this change nothing
class MyObtainAuthToken(auth_views.ObtainAuthToken):
    # btw this function is never called
    def get_serializer_class(self):
        return AuthTokenSerializer

urlpatterns = [
    url(r'^api/users/', include("users.urls")),
    url(r'^api/api-session-auth', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/swagger/$', schema_view),
    url(r'^api/api-token-auth/', MyObtainAuthToken.as_view())
]

I tried to debug the api-token-auth endpoint and in the inspectors.py the get_serializer_field() return an empty array (the line isinstance(serializer, serializers.Serializer)return False when I think she should return True

gfrancqu avatar Oct 24 '17 10:10 gfrancqu

same here

jawahar273 avatar Jan 12 '18 10:01 jawahar273

I got a worse problem. Authorize is not even rendered. Looks like this project is not alive anymore.

arvindnrbt avatar Jan 12 '18 11:01 arvindnrbt

Try with this setting. I think django-rest-swagger has been config to handle the basic auth not the token auth like if you change suddenly no refresh(I don't know the actual reason).

Note: use the key generate after login with the keyword Token 82499d65410bb7ebed6bdecd277537b6b5371b08 for Authorization header. Skip this line if you know what your doing.


SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
    # 'LOGIN_URL': getattr(settings, 'LOGIN_URL', None),
    # 'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None),
    'DOC_EXPANSION': None,
    'APIS_SORTER': None,
    'OPERATIONS_SORTER': None,
    'JSON_EDITOR': False,
    'SHOW_REQUEST_HEADERS': False,
    'SUPPORTED_SUBMIT_METHODS': [
        'get',
        'post',
        'put',
        'delete',
        'patch'
    ],
'VALIDATOR_URL': '',
}

more reference here to the above settings

One more thing need to add

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # uncomment to work with Swagger django docs
        # and comment to work with our application if you get
       # any error on `Authentication` related error
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
}
# there is some issue with approch.

jawahar273 avatar Jan 13 '18 06:01 jawahar273

Is possible to implement the JSONWebAuthentication?

Allan-Nava avatar Apr 23 '18 07:04 Allan-Nava

I have the same probleman. For Fix this I force to put the token at dispatch method.

Example with token

Bernardoow avatar Nov 10 '18 19:11 Bernardoow

I manage to change Swagger's default basic authentication to token authentication with this configuration. Also note, when I added SessionAuthentication to my REST_FRAMEWORK in my settings.py, my api failed to be displayed on swagger docs. Hope this helps

django-rest-swagger==2.2.0 djangorestframework==3.7.7

settings.py

INSTALLED_APPS = [
    'rest_framework',
    'rest_framework_swagger',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    # Parser classes priority-wise for Swagger
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
        'rest_framework.parsers.JSONParser',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ) 
}

# SWAGGER SETTINGS
SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_Key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Token Authorization'
        }
    },
}
  • some helpful documentation https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-definitions-object

jadedh avatar Nov 28 '18 05:11 jadedh

my urls.py

# this is a workaround i tried but this change nothing
class MyObtainAuthToken(auth_views.ObtainAuthToken):
    # btw this function is never called
    def get_serializer_class(self):
        return AuthTokenSerializer

urlpatterns = [
    url(r'^api/users/', include("users.urls")),
    url(r'^api/api-session-auth', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/swagger/$', schema_view),
    url(r'^api/api-token-auth/', MyObtainAuthToken.as_view())
]

I tried to debug the api-token-auth endpoint and in the inspectors.py the get_serializer_field() return an empty array (the line isinstance(serializer, serializers.Serializer)return False when I think she should return True

You have make MyObtainAuthToken inherit from GenericAPIView as well in order to make it possible for DRS to generate its schema. It is explained in this ticket/comment: https://github.com/marcgibbons/django-rest-swagger/issues/629#issuecomment-298806087

dcaragao avatar Feb 05 '19 21:02 dcaragao

I have put bcrypt encryption in my code not python default bcrypt. I am unabale to login with credential. because in user table password store like bcrypt encypted and over that encryption django default encryption. so is there anyway i can add swagger login api first call my bcrypt encryption function after that it try to login.? please comment

bharatperpule avatar Sep 13 '19 10:09 bharatperpule

Even I am getting this issue, we are using docker-compose

  1. I am using Django rest framework for authentication and I am not able to provide authentication token for swagger
  2. All my URLs need authentication

Swagger UI image

Urls.py path('swagger-ui', SwaggerSchemaView.as_view()),

SwaggerSchemaView class SwaggerSchemaView(APIView): _ignore_model_permissions = True exclude_from_schema = True

renderer_classes = [
    CoreJSONRenderer,
    renderers.OpenAPIRenderer,
    renderers.SwaggerUIRenderer
]

def get(self, request):
    generator = SchemaGenerator(
        title='',
        url=None,
        patterns=None,
        urlconf=None
    )
    schema = generator.get_schema(request=request)
    if not schema:
        raise exceptions.ValidationError(
            'The schema generator did not return a schema Document'
        )

    return Response(schema)

SWAGGER_SETTINGS = { "exclude_namespaces": [], # List URL namespaces to ignore "api_version": '0.1', # Specify your API's version "api_path": "/", # Specify the path to your API not a root level "api_key": 'api_key', # An API key "is_authenticated": False, # Set to True to enforce user authentication, "is_superuser": False, # Set to True to enforce admin only access }

Thanks in Advance

kartiki-sahu avatar Sep 26 '19 13:09 kartiki-sahu