Summary: In this tutorial, you will learn what is token authentication and how you can implement it in Django Rest Framework (DRF).

What is Token Authentication?

Token authentication is a method of authenticating a user by providing a token, which is generated by the server and sent to the client, and is then included in subsequent requests made by the client.

The server can then use the token to verify the identity of the user and authorize their actions.

Tokens are often used in place of traditional username and password authentication, as they can be easily revoked or expired, and are more secure.

How to implement Token Authentication in DRF?

Django REST framework (DRF) provides built-in support for token-based authentication with the TokenAuthentication class.

Here is an example of the implementation of token authentication in Django using the Django REST framework:

1. Install the Django REST framework and add it to your INSTALLED_APPS list in your Django project’s settings.py file:

INSTALLED_APPS = [
    # ...
    'rest_framework',
    # ...
]

Make sure to run manage.py migrate after changing your settings.py.

2. Add the following to your project’s urls.py file:

from rest_framework.authtoken import views

urlpatterns = [
    # ...
    path('api-token-auth/', views.obtain_auth_token, name='api_token_auth'),
    # ...
]

This will allow you to obtain a token by making a POST request to /api-token-auth/ with a user’s credentials (username and password).

3. Add the TokenAuthentication class to the authentication classes list in the views that you want to protect with token authentication:

from rest_framework.authentication import TokenAuthentication
from rest_framework.views import APIView

class MyView(APIView):
    authentication_classes = (TokenAuthentication,)

    def get(self, request):
        # Your code here
        return Response(data)

In this example, the MyView class is protected by token authentication. When a client makes a request to this view, the TokenAuthentication class will check for the presence of a valid token in the Authorization header of the request.

If a valid token is found, the request will be authenticated and the user associated with the token will be added to the request’s user attribute.

You can also use the token to authenticate the user in the views and validate the token:

from rest_framework.decorators import authentication_classes

from rest_framework.authentication import TokenAuthentication

@authentication_classes(TokenAuthentication)
def my_view(request):
    # Your code here
    return HttpResponse(data)

4. In your client-side application, you can use the token to authenticate the user by including it in the Authorization header of subsequent requests:

import requests

headers = {'Authorization': 'Token ' + token}
response = requests.get('http://example.com/myview', headers=headers)

How to post username and password to get Token?

To obtain a token with a user’s credentials (username and password), you can make a POST request to /api-token-auth/ endpoint.

Here’s an example of how you can make a POST request in Python using the requests library:

import json
import requests

data = {'username': 'your_username', 'password': 'your_password'}
headers = {'content-type': 'application/json'}
response = requests.post('http://example.com/api-token-auth/', data=json.dumps(data), headers=headers)

if response.status_code == 200:
    token = response.json()['token']
    # Use the token for subsequent requests
    headers = {'Authorization': 'Token ' + token}
    response = requests.get('http://example.com/myview', headers=headers)
    # Do something with the response
else:
    # Handle invalid credentials

You can also use http client libraries like axios, superagent etc to make the post request.

Keep in mind that this will only work if the user credentials are correct, and the user is active.

How to apply Token Authentication to all views?

You will need to add the TokenAuthentication class to the DEFAULT_AUTHENTICATION_CLASSES in your project’s settings.py file, so that it is used by default for all views, unless otherwise specified:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

Why Token Authentication?

There are several advantages of authenticating users with token authentication over traditional username and password authentication:

  1. Statelessness: With token authentication, the server does not need to maintain any session state, which means it can be easily scaled and can handle a large number of concurrent requests.
  2. Mobile-friendly: Tokens can be easily stored on mobile devices and can be included in requests made by the device, making it a good option for mobile applications.
  3. Security: Tokens can be cryptographically signed, which means that the server can be sure that the token was issued by it and that it has not been tampered with. Tokens can also be easily revoked or expired, which makes them more secure than traditional authentication methods.
  4. Decoupling: Tokens can be issued by a separate authentication server, which allows for decoupling of the authentication and resource servers. This means that the resource server can be focused on providing resources and doesn’t need to worry about handling authentication.
  5. Flexibility: Tokens can be used for various purposes such as authentication and authorization. Tokens can be sent to the client in the form of a JWT (JSON Web Token), which can include additional information such as user roles and permissions.

Note that this is just one example of how to implement token authentication in Django, and you may need to adjust it depending on your specific use case.You can also use JWT token authentication which is more secure and you can use JWT library like djangorestframework-jwt or pyjwt to handle jwt tokens.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply