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...

Django pk vs id

 Django pk VS id If you don’t specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one Example: class UserProfile ( models . Model ): name = models . CharField ( max_length = 500 ) email = models . EmailField ( primary_key = True ) def __str__ ( self ): return self . name suppose we have this model. In this model we have make email field as primary key. now django default primary key id field will be gone. It'll remove from database. we can not query as   UserProfile.objects.get(id=1) after make email as primary key this query will throw an error.  Now we have to use pk  Us...

Django Optimization Processes for Write Operation for Postgresql

When optimizing a Django project for large write operations, especially when dealing with PostgreSQL, there are several strategies you can employ to reduce the time it takes to perform these operations: 1. Bulk Inserts In django, we create objects using create()  . Asynchronous version is acreate() .It's a  convenience method for creating an object and saving it all in one step.  and  These are same and equivalent. The create() method is used to create and save a single object in the database. Example: Instead of inserting one row at a time, consider using Django's bulk_create() method to insert multiple rows in a single query. This reduces the overhead of multiple database round trips. Example:  The bulk_create() method is used to create and save multiple objects in the database in a single query. It accepts a list of model instances and inserts them into the database in a single batch operation, which significantly reduces the overhead compared to individ...