JWT Authentication with Django REST Framework
Last Updated :
04 May, 2020
JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in Django.
Modules required :
Basic setup :
Start a project by the following command –
django-admin startproject config
Change directory to project config –
cd config
Start the server- Start the server by typing following command in terminal –
python manage.py runserver
To check whether the server is running or not go to a web browser and enter
http://127.0.0.1:8000/ as URL.
Now stop the server by pressing
ctrl-c
Let’s create an app now called the "app".
python manage.py startapp app
adding configuration to settings.py file :
open settings.py file in config folder and add configuration.
Python3
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
edit urls.py file
open urls.py in config folder
Python3
from django.urls import path, include
from rest_framework_simplejwt import views as jwt_views
urlpatterns = [
path('api/token/',
jwt_views.TokenObtainPairView.as_view(),
name ='token_obtain_pair'),
path('api/token/refresh/',
jwt_views.TokenRefreshView.as_view(),
name ='token_refresh'),
path('', include('app.urls')),
]
edit views.py
open views.py in app folder and make a API view
Python3
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class HelloView(APIView):
permission_classes = (IsAuthenticated, )
def get(self, request):
content = {'message': 'Hello, GeeksforGeeks'}
return Response(content)
edit urls.py
create a urls.py in app folder and edit it
Python3
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.HelloView.as_view(), name ='hello'),
]
Usage :
To make an HTTP request we have used HTTPie, to install it.
$ sudo apt install httpie
Step 1 :
migrate project, create a superuser and runserver
$ python3 manage.py migrate
$ python manage.py createsuperuser
$ python manage.py runserver 4000
Step 2 :
Now, we need to authenticate and obtain the token. which we will get at endpoint is
/api/token/
$ http post http://127.0.0.1:4000/api/token/ username=spider password=vinayak
add your user name and password
Step 3 :
copy access token and make a request
$ http http://127.0.0.1:4000/hello/ "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTg3Mjc5NDIxLCJqdGkiOiIzYWMwNDgzOTY3NjE0ZDgxYmFjMjBiMTBjMDlkMmYwOCIsInVzZXJfaWQiOjF9.qtNrUpyPQI8W2K2T22NhcgVZGFTyLN1UL7uqJ0KnF0Y"
Similar Reads
Basic Authentication - Django REST Framework
Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework provides several authentication schemes. In this section, let's look at the Basic Authentication in Django rest framework, i.e., authenticated against a user's
4 min read
Django Authentication Project with Firebase
Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of components: how to handle user authentication (signing up, signing in, signing out), a management panel for managing our website, how to uploa
7 min read
Implement Token Authentication using Django REST Framework
Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works
2 min read
Joke Application Project Using Django Framework
We will create a simple Joke application using Django. By using the pyjokes package, weâll build a web app that generates and displays random jokes. Weâll go step-by-step to set up the project, configure the views, and render jokes dynamically on the homepage.Install Required PackagesFirst, install
2 min read
How to throttle API with Django Rest Framework
Have you ever passed through an overbridge and noticed the sign stating the bridge weight restriction? Those restrictions are put in place to ensure public safety. Django REST Framework uses a similar process named throttling that controls the rate of requests that the client can make to an API. Thi
4 min read
Securing Django Admin login with OTP (2 Factor Authentication)
Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here â Building Blog CMS (Content
2 min read
Class based views - Django Rest Framework
Class-based views help in composing reusable bits of behavior. Django REST Framework provides several pre-built views that allow us to reuse common functionality and keep our code DRY. In this section, we will dig deep into the different class-based views in Django REST Framework. This article assum
12 min read
Creating and Using Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other conten
3 min read
Using JWT for user authentication in Flask
JWT (JSON Web Token) is a compact, secure, and self-contained token used for securely transmitting information between parties. It is often used for authentication and authorization in web applications. A JWT consists of three parts:Header - Contains metadata (e.g., algorithm used for signing).Paylo
6 min read
Function based Views - Django Rest Framework
Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator. Before
13 min read