Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

How to Implement Token Authentication Using the Django REST Framework

I'm sure you may also find it challenging while implementing token authentication using the Django Rest framework. so here is the solutions that help you out to solve the issue.

  • Als Erste(r) kommentieren

  • Gehören Sie zu den Ersten, denen das gefällt!

How to Implement Token Authentication Using the Django REST Framework

  1. 1. How to Implement Token Authentication Using the Django REST Framework www.bacancytechnology.com
  2. 2. Summary 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 different frameworks, you might face different sorts of chellanges. 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 token-based authentication in the Django REST framework. And that’s why I would like to share this blog post with you that concerns Django REST framework authentication from my personal experience.
  3. 3. Token authentication is essential to know because the code will only proceed further if the authentication runs smoothly. It seems like token is a sort of key containing your identity to open the door and begin with your journey. In this blog, I would like to impart my knowledge regarding how to implement token authentication using the Django REST framework.
  4. 4. 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 common challenges regarding the implementation of the Django REST framework authentication. For your convenience, I have divided this blogpost into various sections to make it simpler. Introduction ‘A Token is a key to unlock the door of your identity and start your journey.’
  5. 5. 1.What is the Django REST framework? 2.How to set up the REST API project? 3.How to implement Token Authentication? 4.How would a user request a Token? 5.Conclusion Content to cover
  6. 6. What is Django REST Framework?
  7. 7. As documentation states, Django REST framework is a powerful and flexible toolkit for building Web APIs. Django REST framework is considered the most flexible and 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 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: 1.Authentication policies include packages for both OAuth1a and OAuth2. 2.Customizable and Flexible 3.Provides etensive usability 4.Serialization supports ORM and non-ORM data. 5.Trusted by international companies.
  8. 8. How to set up the REST API project?
  9. 9. Installation of Django and Django REST framework. Creation of a new project. Navigating to the myproject folder. Starting a new app; here myapp. So far, we have learned about the fundamentals of the Django REST framework and Token Authentication. Moving ahead to the next set-up of the REST API project. You can skip this if you are aware of setting it up. pip install django pip install djangorestframework django-admin startproject myproject cd myproject django-admin startapp myapp
  10. 10. This is how your project structure will be like:
  11. 11. 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.
  12. 12. 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. python manage.py migrate
  13. 13. I hope you are clear about the set-up and migration part so far. Let’s proceed with creating our 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)
  14. 14. 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 in your browser. You can request the response in the form of direct JSON data using this URL http:://
  15. 15. 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 curl http::// http http::// Now, moving further with protecting this endpoint to implement Django REST framework authentication. myproject/myapp/views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated
  16. 16. class DemoView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): content = {'message': 'Hello! This is a Demo'} return Response(content) Try reaccessing the endpoint. http This time you will encounter HTTP 403 Forbidden error. You’ll need token authentication to be done to access this; let’s get our hands on it!
  17. 17. How to Implement Token Authentication?
  18. 18. The implementation of 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 Token Authentication? Perfect! Proceeding further to gain more knowledge about its implementation. To carry through the Django REST Framework Authentication scheme, add this in the settings.py file to configure the authentication. myproject/settings.py
  19. 19. 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.TokenAuthenti cation', ], }
  20. 20. 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 authentication tokens. python manage.py migrate 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 simon@test.com For generating the token, just in case you want to test it, the command-line utility is most comfortable again. python manage.py drf_create_token simon
  21. 21. 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 9054f7aa9305e012b3c2300408c3cddf390fcdde Try to make one more request to our endpoint /demo/ http You will observe that some extra information has been displayed on your screen. This the time for using the token finally! http 'Authorization: Token 9054f7aa9305e012b3c2300408c3cddf390fcdde'
  22. 22. Yes, that’s it! Now for your every request, you need to use Authorization: Token 9054f7aa9305e012b3c2300408c3cddf390fcdde 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- curl -H 'Authorization: Token 9054f7aa9305e012b3c2300408c3cddf390fcdde' Or if it is said to be a Python requests call, you should follow this-
  23. 23. import requests url = '' 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-
  24. 24. 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.
  25. 25. How would a user request a Token?
  26. 26. 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'), ]
  27. 27. Let’s inspect our brand new endpoint /token-auth/ http It won’t handle GET requests. It will inform you to use POST request with username and password. Try this command. http post username=simon password=1234
  28. 28. 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 check that further and start exploring token authentication.
  29. 29. I hope your purpose of landing on this blog post to understand 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 Tehnology today. Our dedicated Python developers are well-versed at 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. Conclusion
  30. 30. Thank You