SlideShare a Scribd company logo
1 of 30
Download to read offline
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

More Related Content

Similar to How to Implement Token Authentication Using the Django REST Framework

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 FrameworkInexture Solutions
 
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 applicationKaty Slemon
 
Implementation of ssl injava
Implementation of ssl injavaImplementation of ssl injava
Implementation of ssl injavatanujagrawal
 
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 ...Ganesh Kumar
 
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...izzatisholehah
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptaljbsysatm
 
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 - #OpenWestJoshua Warren
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
Web driver selenium simplified
Web driver selenium simplifiedWeb driver selenium simplified
Web driver selenium simplifiedVikas Singh
 
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 developeraWebExpo
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8Asika Kuo
 
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.Netalsmola
 
Full Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication SystemFull Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication SystemDigamber Singh
 
Whys and Hows of Automation
Whys and Hows of AutomationWhys and Hows of Automation
Whys and Hows of AutomationvodQA
 
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)Katy Slemon
 
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.docxTechnogeeks
 
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 jsStormpath
 

Similar to 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
 

More from Katy Slemon

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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 
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.pdfKaty Slemon
 

More from 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
 

Recently uploaded

A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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 WorkerThousandEyes
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Recently uploaded (20)

A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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