almost 4 years ago

## How to use Django REST Framework's Token Based Authentication

To enable token based authentication using DRF, the following steps need to be done (I am using Django 1.8.5 and DRF 3.2.4):

1. Do the following things BEFORE you create the superuser. Otherwise, the superuser does not get his/her token created.

2. Go to settings.py and add the following:

1. Add the following code in myapp's models.py:

Alternatively, if you want to be more explicit, create a file named signals.py under myapp project. Put the code above in it, then in init.py, write import signals

1. Open up a console window, navigate to your project dir, and enter the following command:

Take a look in your database, a table named authtoken_token should be created with the following fields: key (this is the token value), created (the datetime it was created), user_id (a foreign key that references the auth_user table's id column)

1. create a superuser with python manage.py createsuperuser. Now, take a look at the authtoken_token table in your DB with select * from authtoken_token;, you should see a new entry has been added.

2. Using curl or a much simpler alternative httpie to test access to your api, I am using httpie:

That's it. From now on, for any API access, you need to include the following value in the HTTP header (pay attention to the whitespaces):

1. (Optional) DRF also provides the ability to return a user's token if you supply the username and password. All you have to do is to include the following in urls.py:

Using httpie to verify:

In the return body, you should see this:

#### Improvements

DRF's token implementation lacks a few important features:

• Tokens do not rotate
• Tokens do not expire
• The same token is shared among all the clients (PC browsers, smartphones, tablets, etc.)

The Django Oauth Toolkit should be considered as a step up.