0
0
Rest APIprogramming~5 mins

JWT structure and flow in Rest API

Choose your learning style9 modes available
Introduction

JWT helps safely share information between two parties. It makes sure the data is real and not changed.

When a website needs to remember who you are after you log in.
When a mobile app talks to a server and needs to prove your identity.
When different parts of a system need to share user info securely.
When you want to avoid sending your password every time you ask for data.
Syntax
Rest API
header.payload.signature

The JWT has three parts separated by dots.

Each part is base64 encoded text.

Examples
This is a full JWT example with header, payload, and signature.
Rest API
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSIsIm5hbWUiOiJKb2huIERvZSJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Shows the JSON content inside each part before encoding.
Rest API
{
  "alg": "HS256",
  "typ": "JWT"
}.
{
  "userId": "12345",
  "name": "John Doe"
}.
Signature
Sample Program

This program creates a JWT token with user info, then decodes it back to show the data.

Rest API
import jwt

# Secret key to sign the token
secret = 'mysecretkey'

# Data to include in the token
payload = {'userId': '12345', 'name': 'John Doe'}

# Create a JWT token
encoded_jwt = jwt.encode(payload, secret, algorithm='HS256')
print('JWT Token:', encoded_jwt)

# Decode the JWT token
decoded_payload = jwt.decode(encoded_jwt, secret, algorithms=['HS256'])
print('Decoded Payload:', decoded_payload)
OutputSuccess
Important Notes

The header tells what algorithm is used to sign the token.

The payload holds the data you want to share.

The signature proves the token is not changed and is from a trusted source.

Summary

JWT has three parts: header, payload, and signature.

It is used to safely share data between systems.

Tokens are signed to prevent tampering.