27
votes

I'm following the DRF docs to setup TokenAuthentication, and can't get it working with the browsable API. I believe I've added the proper lines in settings.py:

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

INSTALLED_APPS = (
   ...
'rest_framework',
'rest_framework.authtoken',
   ...

As well as generated tokens for existing users with the code snippet from the docs. I can see tokens for each user if I query the authtoken_token table, so I know they exist.

Everytime I try to log in to the browsable API, I get the following content returned:

HTTP 401 Unauthorized
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: Token

{
"detail": "Authentication credentials were not provided."
}

So it appears to be attempting Token authentication, but this message is a little odd. When I enter an incorrect password, I get the 'enter a correct password' message on the login form. When I enter the correct password, it appears to login, but takes me to the API root with the above message, and displays "Log In" on the top menu, rather than the username.

Could this be related to my custom user model somehow? Or could it be due to the fact that I'm currently developing with the dev server, which doesn't support https- the DRF docs mention needing HTTPS with TokenAuthentication, though I wasn't sure if that was a best practice or actually required.

3

3 Answers

33
votes

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',
),
5
votes

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.

2
votes

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