Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: using TokenAuthentication with browsable API

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.

like image 762
dkhaupt Avatar asked Feb 24 '16 11:02

dkhaupt


People also ask

What is browsable API in Django REST Framework?

The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header.

How do I add login to the browsable API provided by DRF?

Adding login to the Browsable API In order to do so we'd need to be able to login as a user. We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file. And, at the end of the file, add a pattern to include the login and logout views for the browsable API.


1 Answers

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', ), 
like image 88
ilse2005 Avatar answered Sep 22 '22 03:09

ilse2005