Skip to main content

Importance JWT and How Do JWTs Work in Django

Importance of JWT




JWT (JSON Web Token) is a form of transmitting a JSON object as information between parties. Let's learn more about what JWTs are and how they work.

JWTs are important for two main reasons:

1. Authorization
2. Information exchange

JSON Web Token comprises 3 strings separated by “.” as follows where each part is encoded with base64url encoding :


“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjp7ImlkIjoiNTlhZDFmZTI0MDVkNzk0YTFkYWQ2YmFkIiwiZGlzcGxheV9uYW1lIjoiQWRtaW4iLCJyb2xlX3R5cGUiOiJhZG1pbiJ9LCJpZCI6IlwiNTliYmJjODc0MDVkNzk0NjYwNGEzZjUyXCIiLCJlbWFpbCI6Imp5b3RpZ2F1dGFtMTA4QGdtYWlsLmNvbSJ9.oGA-goFi7ee6DdKn0Z4sctomaY6Ki0mfuJfxT4OK9WA”


1. Header
2. Payload
3. Signature


Header:
The header contains:
    type: the specification that the token is a JWT
    algorithm: the signing algorithm used to sign said token



Algorithms that are used to sign include RSA, HMAC, or SHA256. The signatures for the tokens serve two purposes – integrity and authenticity.

{ "typ":"JWT", "alg":"HS256" }


Payload:

The payload contains the claims, which are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims. These are also Base64Url encoded to form the second part of the JWT.

There are three types of claims: 
1. Registered claims: they include exp (expiration time), iss (issuer), sub (subject) and aud (audience). They are highly recommended since they provide information on the use and condition of use of the token. 
2.Public claims: these are claims that are unique to avoid collisions with other services that use JWT. 
3.Private claims: these are claims that are used specifically between two parties that understand the meaning and use. Like the example of my medals, my games master and I understood the value.


Below is an example of what a payload looks like.

{

  "token_type": "access",

  "exp": 1543828431,

  "jti": "7f5997b7150d46579dc2b49167097e7b",

  "user_id": 4

}



token_type is a label that shows what kind of token this is. Case in point, it's an access token. 

exp stands for expiration. It's the time the token will stop working – in this case the number represents date and time in Unix time. 

jti stands for JWT ID. It's a unique identifier for this specific token. The ID is used to keep track of which tokens have been used, to prevent use of the same token more than once. 

user_id:  is an identifier of the user this token belongs to. In this case, the number 4 is the user identification.


Signature

It is most important part of JSON Web Token. Header and Payload is encoded using Base64url encoding. Then these two are concatenated with a separator. And whole code is provided to the client in the authentication process.


HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)


“SECRET” A signature held by server 

How Does JWT Works ?

In authentication process whenever a user or client wants to login to the web application, then user need to send their login credentials like username or password to server and request for a JWT token form the server.

Then server provide a JWT to the User only when user is verified. User then send that token to the server back to request for the accessToken to access the information of their own. The server checks and verify whether the accessToken is valid or not. If the token is verified then user can successfully login to their account and access their own information stored in the database.








Comments

Popular posts from this blog

Implementing Advance Query Optimization in Django ORM

 Django's ORM makes database interactions seamless, allowing developers to write queries in Python without raw SQL. However, as applications scale, inefficient queries can slow down performance, leading to high latency and database load.  This guide explores advanced query optimization techniques in Django ORM to go beyond basic CRUD (Create, Read, Update, Delete) operations and improve efficiency.  1. Use QuerySet Caching to Avoid Repeated Queries Using cache reduces redundant queries for frequently accessed data. Caching helps reduce repeated database hits. 2. Avoid .count() on Large Datasets Using .count() on large tables can be expensive Inefficient way: Optimized way ( .exists() is Faster) 3. Use Indexes for Faster Lookups Indexes speed up queries on frequently filtered fields. Add db_index=True for frequently queried fields: 4. Optimize Bulk Inserts and Updated Performing operations on multiple records one by one is inefficient. Use bulk_create() for mass insert...

Database Indexing in Django application

  Database Indexing Database indexing is a technique used to optimize the performance of database queries by allowing the database management system (DBMS) to quickly locate and retrieve specific rows of data. Indexes are data structures that provide a faster way to look up records based on the values stored in one or more columns of a table. When you create an index on a table, the DBMS creates a separate data structure that maps the values in the indexed columns to the corresponding rows in the table. Default Type of Index is B-Tree Index ( The king of all indexes) বইতে কোন টপিক খুজতে গেলে আমরা টেবিল অফ কনটেন্ট থেকে দেখি এই টপিক কত নম্বর পেজে আছে।যাতে করে আমাদের পুরো বই খুজতে না হয়। ডেটাবেজ ইনডেক্সিং ও তেমনই একটা ইফিসিয়েন্ট টেকনিক।ডেটাবেজে কোন ডেটাকে দ্রুত খুজে বের করার জন্য ইনডেক্সিং করা লাগে।যদি এমন হয় একটা কুয়েরি বার বার এক্সিকিউট করতে হচ্ছে এবং একটা কলাম থেকে ভ্যালু বার বার খুজতে হচ্ছে তখন আমরা সেই কলামে ইনডেক্সিং করতে পারি।এর মাধ্যমে কোন ডেটা দ্রুত রিট্রাইভ করা যায়।কিন্তু ই...

Django select_related and prefetch_related

  Difference between select_related and prefetch_related Reducing SQL queries is one of the first steps when optimizing a Django project. There are two powerful methods included in the Django ORM to help us that can boost performance by creating a single more complex QuerySet rather than multiple, smaller queries. In this project we will understand about  select_related and prefetch_related.  Django use these two orm method to reduce sql queries in database based on different scenario.  select_related Lets assume  this two model we have.  class Author ( models . Model ): name = models . CharField ( max_length = 200 ) def __str__ ( self ): return self . name class Courses ( models . Model ): name = models . CharField ( max_length = 200 ) author = models . ForeignKey ( Author , on_delete = models . CASCADE , related_name = 'courses' ) def __str__ ( self ): return self . name Here we have two mode. ...