[Django]-Django REST Framework: using TokenAuthentication with browsable API

37👍

You can’t use the browsable api with TokenAuthentication. You have to add SessionAuthtication to your settings (http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication):

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),

7👍

You can use a browser plugin to set token in the header. I’m using Modheader which is free.

The example of setting the header:

set header in modheader

I wrote a blog post on how this can be done: link to post.

I like this solution because you don’t need to change the auth classes.

1👍

I did:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),

and I added a custom auth class in api.py

class CustomAuthToken(ObtainAuthToken):

    authentication_classes = [TokenAuthentication]

    def post(self, request, *args, **kwargs):
        ...
        return Response({...})

See https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint

Leave a comment