It’s been a long I’ve been using different Python frameworks. However, I’m more comfortable with the Django REST framework. When you are working with other Python different frameworks, you might face different sorts of challenges. I personally find it challenging to implement token-based authentication in most cases.
I realized that the problem behind the challenge is not its implementation but its actual usage. And it seems intriguing to me, so I thought to dig deeper into this topic. I’m sure you may also find it challenging to use the Django REST framework token authentication. And that’s why I would like to share this blog post with you that concerns Django REST framework authentication from my personal experience.
Token authentication is essential to know because the code will only proceed further if the authentication runs smoothly. It seems like a token is a sort of key containing your identity to open the door and begin your journey. In this blog, I would like to impart my knowledge regarding how to implement token authentication using the Django REST framework. So, what are we waiting for? Let’s begin with the Django REST framework authentication tutorial.
‘A Token is a key to unlock the door of your identity and start your journey.’
Let me make it simple for you, Token-based Authentication works on the exchange of username and password for its token, which will be used further in all the requests made to verify that user on the server-side and to provide permission to proceed. Let’s read further and get through the everyday challenges regarding implementing the Django REST framework token authentication.
As documentation states, Django REST framework is a powerful and flexible toolkit for building Web APIs.
Django REST framework is considered the most comfortable Python framework that lets you create RESTful APIs at your ease. It provides an easier way for data transmission between the interface and the database. It communicates with data storage and the user interface via the .json file. It will separate data storage and the user interface; it will communicate both via the .json file.
Now the question might arise why one should choose the Django REST framework from different Python frameworks. Here are some reasons which would back up your choice:
This was enough overview regarding the Django REST framework. Let’s get our hands-on coding and start with the Django REST framework Token Authentication example.
So far, we have learned about the fundamentals of the Django REST framework and Token Authentication individually. Moving ahead for how to create REST API project and install Django.
You can skip this if you are aware of setting it up. You can skip this if you are aware of setting it up.
myproject/ |-- myapp/ | |-- migrations/ | |-- __init__.py | |-- admin.py | |-- apps.py | |-- models.py | |-- tests.py | +-- views.py |-- __init__.py |-- settings.py |-- urls.py +-- wsgi.py manage.py
Now further add the main app, which you’ve created, and the rest_framework, which you’ve installed to INSTALLED_APPS, which is inside module named settings.py.
// myproject/settings.py
INSTALLED_APPS = [ # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-Party Apps 'rest_framework', # (Your project's apps) 'myproject.myapp', ]
To install the app and update the database with this new model, it is necessary to return to the project root, where the manage.py script is located, and run this command for migration.
I hope you are clear about the REST API project set-up and Django migration part so far. Let’s proceed with creating our Django first API view for testing it out. myproject/myapp/views.py
from rest_framework.views import APIView from rest_framework.response import Response class DemoView(APIView): def get(self, request): content = {'message': 'Hello! This is a Demo!'} return Response(content)
Now the second step is to register the path.
// myproject/urls.py
from django.urls import path from myproject.myapp import views urlpatterns = [ path('demo/', views.DemoView.as_view(), name='demo'), ]
So, an API with one endpoint, /demo/, to perform GET requests is ready.
You can test this API by accessing http://127.0.0.1:8000/demo/ in your browser. You can request the response in the form of direct JSON data using this URL http:://127.0.0.1:8000/demo/?format=json.
I prefer the command line more as it is easy to play with request headers, and if you are comfortable using it as well, try either use cURL or HTTPie
Now, moving further with protecting this endpoint to implement Django REST framework token authentication.
// myproject/myapp/views.py
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated class DemoView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): content = {'message': 'Hello! This is a Demo'} return Response(content)
Try reaccessing the endpoint.
This time you will encounter HTTP 403 Forbidden error. You’ll need token authentication to be done to access this; let’s get started with it!
Dealing with Django Token Authentication is quite difficult compared to other Authentication Schemes, so be patient and digest this step by step. So, are you ready to learn about DjangoToken Authentication? Perfect! Proceeding further to gain more knowledge about its implementation.
To carry through the Django REST Framework Token Authentication scheme, add this in the settings.py file to configure the authentication.
// myproject/settings.py
INSTALLED_APPS = [ # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-Party Apps 'rest_framework', 'rest_framework.authtoken', # (Your project's apps) 'myproject.myapp', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], }
I would like to draw your attention to the difference between other authentication schemes and the Django REST Framework Authentication Scheme; that is, you need to add the app to the array of INSTALLED_APPS. Now migrate the database for creating the table to store auth tokens for authentication.
After the migration is successfully done, you need to create a user and use the manage.py command-line utility.
python manage.py createsuperuser --username simon --email [email protected]
For generating the auth token, just in case you want to test it, the command-line utility is most comfortable again.
You will receive a generated token after running the above command. For example, let’s assume the random string generated, which you will use for token authentication, is
Try to make one more request to our endpoint
You will observe that some extra information has been displayed on your screen. This the time for using the token finally!
Yes, that’s it! Now for your every request, you need to use
in your header part so it can be authenticated on the server-side and proceed with the request further. In case you are using cURL, you should run this command-
Or if it is said to be a Python requests call, you should follow this-
import requests url = 'http://127.0.0.1:8000/demo/' headers = { 'Authorization': 'Token 9054f7aa9305e012b3c2300408c3cddf390fcdde' } r = requests.get(url, headers=headers)
Or if you want to use Angular, you should use HttpInterceptor and set your header like this-
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(request: HttpRequest, next: HttpHandler): Observable> { const user = JSON.parse(localStorage.getItem('user')); if (user && user.token) { request = request.clone({ setHeaders: { Authorization: `Token ${user.accessToken}` } }); } return next.handle(request); } }
So the implementation of token-based authentication is completed. Let’s dive deeper into the Django REST Framework Authentication to explore more.
We have seen the first half of the Django REST framework Token Authentication, now let’s see the second half, i.e., how would a user request an auth token in Django to login and proceed further.
The Django REST Framework will provide an endpoint so that the user can request a Token for authentication with their password and username.
For that, please include the following route to your urls.py
// myproject/urls.py
from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from myproject.myapp import views urlpatterns = [ path(demo/', views.DemoView.as_view(), name='demo'), path('token-auth/', obtain_auth_token, name='api_token_auth'), ]
Let’s inspect our brand new endpoint
It won’t handle GET requests. It will inform you to use POST request with username and password. Try this command.
You will get a particular token associated with the user. Don’t forget to store the token for all future authentication requests. Even if the purpose of token authentication is similar, your way of making the POST requests will depend on which technology/framework/language you are using. There are different suggestions for how and where to store the token for various applications. You can click here and learn about Token Storage.
I hope your purpose of landing on this blog post to understand token implementation with Django REST framework authentication is served. If you are looking for assistance with the Django REST framework and a helping hand, then get in touch with Bacancy Technology today. Our dedicated Python developers are well-versed in offering top-of-the-line Python development services for mission-critical software projects. We also let you hire Python developer from us at your convenience, time zone, and engagement model to get the job done. We will ensure that all your requirements will be 100% fulfilled as client satisfaction is our highest priority.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.