Home > Blockchain >  Why isn't Django Rest Framework Token Authentication working?
Why isn't Django Rest Framework Token Authentication working?

Time:11-24

I am currently using Django rest framework and trying to implement a Token Authentication system. Currently, my settings.py looks like this:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication'
    ]
}

and rest_framework.authtoken is in installed_apps.

My urls.py looks like this:

urlpatterns = [
    ...
    url('^v1/users/$', views.users_view),
    ...
]

My views.py looks like this:

@authentication_classes((TokenAuthentication,))
@api_view(['PUT', 'POST'])
def users_view(request):
...

I'm working in postman to test the API and regardless of whether I put the token in the authorization field, the API works as intended. What do I need to change for the token authentication to work as intended?

Update: Reqbin is also giving me the same functionality so I don't think it's a problem with postman.

CodePudding user response:

You need to add permission class as well.

@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
@api_view(['PUT', 'POST'])
def users_view(request):
...

CodePudding user response:

It appears there is a bug in Django that won't allow some authentications to work with function based views. I can confirm it doesn't work for TokenAuthentication and needed to use class based views.

  • Related