SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
How to
Implement
Token
Authentication
Using the
Django REST
Framework
www.bacancytechnology.com
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.
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.
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.’
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
What is
Django REST
Framework?
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.
How to set up
the REST API
project?
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
This is how
your project
structure will
be like:
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.
python manage.py migrate
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)
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
curl http:://127.0.0.1:8000/demo/
http http:://127.0.0.1:8000/demo/
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
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 http://127.0.0.1:8000/demo/
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!
How to
Implement
Token
Authentication?
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
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',
],
}
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
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 http://127.0.0.1:8000/demo/
You will observe that some extra information
has been displayed on your screen. This the time
for using the token finally!
http http://127.0.0.1:8000/demo/ 'Authorization:
Token
9054f7aa9305e012b3c2300408c3cddf390fcdde'
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 http://127.0.0.1:8000/demo/ -H
'Authorization: Token
9054f7aa9305e012b3c2300408c3cddf390fcdde'
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.
How would a
user request a
Token?
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
/token-auth/
http http://127.0.0.1:8000/token-auth/
It won’t handle GET requests. It will inform you
to use POST request with username and
password. Try this command.
http post http://127.0.0.1:8000/token-auth/
username=simon password=1234
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.
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
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Process management in os
Process management in osProcess management in os
Process management in os
Miong Lazaro
 
Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...
Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...
Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...
Simplilearn
 
Xen Project Contributor Training Part 3 - Communication v1.0
Xen Project Contributor Training Part 3 - Communication v1.0Xen Project Contributor Training Part 3 - Communication v1.0
Xen Project Contributor Training Part 3 - Communication v1.0
The Linux Foundation
 

Was ist angesagt? (20)

Trace memory leak with gdb (GDB로 메모리 누수 찾기)
Trace memory  leak with gdb (GDB로 메모리 누수 찾기)Trace memory  leak with gdb (GDB로 메모리 누수 찾기)
Trace memory leak with gdb (GDB로 메모리 누수 찾기)
 
Apache PIG
Apache PIGApache PIG
Apache PIG
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programming
 
Advanced Hadoop Tuning and Optimization - Hadoop Consulting
Advanced Hadoop Tuning and Optimization - Hadoop ConsultingAdvanced Hadoop Tuning and Optimization - Hadoop Consulting
Advanced Hadoop Tuning and Optimization - Hadoop Consulting
 
Process management in os
Process management in osProcess management in os
Process management in os
 
Big Data - 25 Amazing Facts Everyone Should Know
Big Data - 25 Amazing Facts Everyone Should KnowBig Data - 25 Amazing Facts Everyone Should Know
Big Data - 25 Amazing Facts Everyone Should Know
 
Hadoop File system (HDFS)
Hadoop File system (HDFS)Hadoop File system (HDFS)
Hadoop File system (HDFS)
 
Raid 1 and raid 5 configuration in windows server
Raid 1 and raid 5 configuration in windows serverRaid 1 and raid 5 configuration in windows server
Raid 1 and raid 5 configuration in windows server
 
File Management – File Concept, access methods, File types and File Operation
File Management – File Concept, access methods,  File types and File OperationFile Management – File Concept, access methods,  File types and File Operation
File Management – File Concept, access methods, File types and File Operation
 
Big data Hadoop presentation
Big data  Hadoop  presentation Big data  Hadoop  presentation
Big data Hadoop presentation
 
process creation OS
process creation OSprocess creation OS
process creation OS
 
Ch7 Process Synchronization galvin
Ch7 Process Synchronization galvinCh7 Process Synchronization galvin
Ch7 Process Synchronization galvin
 
Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...
Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...
Hadoop Architecture | HDFS Architecture | Hadoop Architecture Tutorial | HDFS...
 
2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요
2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요
2011 H3 컨퍼런스-파이썬으로 클라우드 하고 싶어요
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
 
Xen Project Contributor Training Part 3 - Communication v1.0
Xen Project Contributor Training Part 3 - Communication v1.0Xen Project Contributor Training Part 3 - Communication v1.0
Xen Project Contributor Training Part 3 - Communication v1.0
 
Hadoop & Big Data benchmarking
Hadoop & Big Data benchmarkingHadoop & Big Data benchmarking
Hadoop & Big Data benchmarking
 
INTRODUCTION TO BIG DATA AND HADOOP
INTRODUCTION TO BIG DATA AND HADOOPINTRODUCTION TO BIG DATA AND HADOOP
INTRODUCTION TO BIG DATA AND HADOOP
 
Kernels and its types
Kernels and its typesKernels and its types
Kernels and its types
 
H.264 nal and RTP
H.264 nal and RTPH.264 nal and RTP
H.264 nal and RTP
 

Ähnlich wie How to Implement Token Authentication Using the Django REST Framework

Implementation of ssl injava
Implementation of ssl injavaImplementation of ssl injava
Implementation of ssl injava
tanujagrawal
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
Joshua Warren
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8
Asika Kuo
 

Ähnlich wie How to Implement Token Authentication Using the Django REST Framework (20)

Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
 
How to implement sso using o auth in golang application
How to implement sso using o auth in golang applicationHow to implement sso using o auth in golang application
How to implement sso using o auth in golang application
 
Implementation of ssl injava
Implementation of ssl injavaImplementation of ssl injava
Implementation of ssl injava
 
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
A Detailed Guide to Securing React applications with Keycloak  - WalkingTree ...A Detailed Guide to Securing React applications with Keycloak  - WalkingTree ...
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
 
validation of user credentials in social network by using Django backend aut...
validation of user credentials in social network by using  Django backend aut...validation of user credentials in social network by using  Django backend aut...
validation of user credentials in social network by using Django backend aut...
 
Introduce Django
Introduce DjangoIntroduce Django
Introduce Django
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Web driver selenium simplified
Web driver selenium simplifiedWeb driver selenium simplified
Web driver selenium simplified
 
Petr Dvořák: Mobilní webové služby pohledem iPhone developera
Petr Dvořák: Mobilní webové služby pohledem iPhone developeraPetr Dvořák: Mobilní webové služby pohledem iPhone developera
Petr Dvořák: Mobilní webové služby pohledem iPhone developera
 
- Webexpo 2010
- Webexpo 2010- Webexpo 2010
- Webexpo 2010
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8
 
Top Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.NetTop Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.Net
 
Full Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication SystemFull Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication System
 
Whys and Hows of Automation
Whys and Hows of AutomationWhys and Hows of Automation
Whys and Hows of Automation
 
Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)
 
What is Full Stack with Django and how to start learning It.docx
What is Full Stack with Django and how to start learning It.docxWhat is Full Stack with Django and how to start learning It.docx
What is Full Stack with Django and how to start learning It.docx
 
How to Use Stormpath in angular js
How to Use Stormpath in angular jsHow to Use Stormpath in angular js
How to Use Stormpath in angular js
 

Mehr von Katy Slemon

Mehr von Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

How to Implement Token Authentication Using the Django REST Framework

  • 1. How to Implement Token Authentication Using the Django REST Framework www.bacancytechnology.com
  • 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. 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. 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. 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
  • 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. How to set up the REST API project?
  • 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. This is how your project structure will be like:
  • 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. 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. 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. 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.
  • 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:://127.0.0.1:8000/demo/ http http:://127.0.0.1:8000/demo/ 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. 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 http://127.0.0.1:8000/demo/ 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!
  • 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. 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. 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. 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 http://127.0.0.1:8000/demo/ You will observe that some extra information has been displayed on your screen. This the time for using the token finally! http http://127.0.0.1:8000/demo/ 'Authorization: Token 9054f7aa9305e012b3c2300408c3cddf390fcdde'
  • 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 http://127.0.0.1:8000/demo/ -H 'Authorization: Token 9054f7aa9305e012b3c2300408c3cddf390fcdde' Or if it is said to be a Python requests call, you should follow this-
  • 23. 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-
  • 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. How would a user request a Token?
  • 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. Let’s inspect our brand new endpoint /token-auth/ http http://127.0.0.1:8000/token-auth/ It won’t handle GET requests. It will inform you to use POST request with username and password. Try this command. http post http://127.0.0.1:8000/token-auth/ username=simon password=1234
  • 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. 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