Token Authentication and Django Framework

Humberto Rayashi
Aug 11 · 2 min read

Hello guys, today we gonna talk about how to configure a Django API project in order to authenticate users using token-based authentication.

The most used approach nowadays to secure the Web API resources is by authenticating the users in the Web API server by using the signed token.

How token-based authentication works?

The process of authenticating users using token is quite simple:

1 — In the client application user send the username and password to the server;

2 — If username and password are correct, then server create or get a unique token for this user, and send back to the client application;

3 — Then client application store this token, in order to send back in the header of all HTTP request;

4 — Server identify the user by this token.

Token-based authentication process

Installing and configure Django Rest Framework

First, we need to install the Django Rest Framework in our project

pip install djangorestframework

Add 'rest_framework' to your INSTALLED_APPS setting.

After changing these settings you need to run migrate command, this will create a table that contains all users tokens in your database.

Now we need to generate a token automatically for all created user, let's catch the user post_save signal

All done! Now your API is ready to work with token-based authentication, you can authenticate users in web and mobile applications.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade