Django Rest Framework DRF token authentication with expires in

Erkebulan Duisebay
3 min readOct 25, 2018

--

Here I want to describe how to implement token authentication in DRF with expires in. You need to take 4 steps to implement it.

Firstly, we have to prepare our environment

Virtual environment is needed for holding your packages separately from global package version. The link for full documentation. Create the virtual environment and activate it with a following commands:

python3 -m venv app
source app/bin/activate

Install Django and DRF

Inside a same folder, install Django and Django rest framework in our virtualenv.

django-admin startproject apps
pip install djangorestframework

Then we have to create app users.

python manage.py startapp users

Secondly, We have to configure our project

Inside a settings.py add rest_framework and rest_framework.authtoken inside istalled_apps

After that we configure REST_FRAMEWORK. Here we will specify 2 thing.

  1. Authentication: is the process of determining whether someone or something is, in fact, who or what it declares itself to be.
  2. Permission: the action of officially allowing someone to do a particular thing.

Here we specify that our authentication is based on TokenAuthentication, but further we create our custom Authentication with expires token. Permission show that by default only authenticated person have permission to our system.

Thirdly, we implement sign in method

Here displayed how to implement a signin function which return a token associated with the user.

Below shown how to implement token_expire_handler function

The simple implementation of UserSigninSerializer is displayed below.

Now we have to set route to our signin function

Fourth, token expire in authentication

Here we will create new DEFAULT_AUTHENTICATION_CLASSES which will check expire time of token and named it ExpiringTokenAuthentication.

And now we have to add this class to our default authentication class in settings.y

That is it. Now we implement token Authentication with expire time.

Testing

We need to create user and sign up system. In my case, I will use superuser for demonstration

python manage.py createsuperuser

To test our app we create function user_info which will return a information about user. The simple implementation shown below.

And add this function to urls

We test the system with postman.

First we make request to server without token. And system successfully reject our request.

Secondly we sign in with username and password.Server return to us user info and token.

Lastly we make request to get_info with our token. Make sure that you add key word Token before providing token itself.

it works.

It is simple token authentication. If you notice any error inform me in comment. Any best practices and suggestions welcome.

In settings.py add this one:
TOKEN_EXPIRED_AFTER_SECONDS = 86400
simply it will tell how long your token will be active.

--

--