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

WSGI vs ASGI: What Every Django Developer Should Know !

  If you've been developing with Django, you've probably come across WSGI (Web Server Gateway Interface), the trusted friend of all traditional, synchronous web apps. But in this fast-moving, real-time world, you may have also heard about its dynamic, asynchronous cousin ASGI (Asynchronous Server Gateway Interface). WSGI (Web Server Gateway Interface): 1. The OG (original) Django interface, designed for synchronous HTTP requests. 2. Perfect for blogs, CMS, e-commerce, and standard web apps. 3. Uses servers like Gunicorn or uWSGI. 4. Limited to handling one request at a time. ASGI (Asynchronous Server Gateway Interface): 1. The modern, scalable interface designed for asynchronous web apps. 2. Ideal for handling WebSockets, HTTP/2, and real-time features like chat apps. 3. Built for high concurrency; uses Uvicorn, Daphne, or similar ASGI servers. 4. Allows you to leverage Python’s async and await for non-blocking code. When to Choose What: WSGI: Traditional apps where synchronou...

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

Sum of numbers 1 to N

 Problem: We need the sum of the number 1 to N. The N could be anything (100,200,500,33,21) like anything. What is the best approach to solve this little problem ?  so there are multiple way to solve this problem.  We will discuss 3 solution .  1. Recursive way  : Using recursion we can solve this problem. Here is the solution The time complexity of this code is O(n) because it makes n recursive calls, each of which takes constant time.  The space complexity is also O(n) because each recursive call adds a level to the call stack. The maximum depth of the recursion is n, so the maximum amount of space on the call stack is proportional to n. 2. Using loop Here we need 2 different variables in our code -- a variable where we can store the sum as we iterate through the values and add them (my_sum in my code), and another variable (i in my code) to iterate over the numbers from 0 to n. The time complexity of this code is O(n). The while loop runs n+1 times, and ...