How to Implement Token Authentication using Django REST Framework

In this tutorial you are going to learn how to implement Token-based authentication using Django REST Framework (DRF). The token authentication works by exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.

The specifics of how the authentication is handled on the client side vary a lot depending on the technology/language/framework you are working with. The client could be a mobile application using iOS or Android. It could be a desktop application using Python or C++. It could be a Web application using PHP or Ruby.

But once you understand the overall process, it’s easier to find the necessary resources and documentation for your specific use case.

Token authentication is suitable for client-server applications, where the token is safely stored. You should never expose your token, as it would be (sort of) equivalent of a handing out your username and password.

Table of Contents

  • Setting Up The REST API Project (If you already know how to start a DRF project you can skip this)
  • Implementing the Token Authentication
  • User Requesting a Token
  • Conclusions

Setting Up The REST API Project

So let’s start from the very beginning. Install Django and DRF:

pip install django
pip install djangorestframework

Create a new Django project: startproject myapi .

Navigate to the myapi folder:

cd myapi

Start a new app. I will call my app core: startapp core

Here is what your project structure should look like:

 |-- core/
 |    |-- migrations/
 |    |--
 |    |--
 |    |--
 |    |--
 |    |--
 |    +--

Add the core app (you created) and the rest_framework app (you installed) to the INSTALLED_APPS, inside the module:


    # Django Apps

    # Third-Party Apps

    # Local Apps (Your project's apps)

Return to the project root (the folder where the script is), and migrate the database:

python migrate
Back to Top