Skip to main content

JWT Token Generation Guide

This guide explains how to generate a JWT (JSON Web Token) for API authorization with TATA 1mg Order APIs. Below, you'll find examples in multiple programming languages to help you integrate seamlessly.

What is a JWT Token?

A JWT token is a secure way to authenticate API requests. The token contains encoded information and is signed using a private key. It's passed in the Authorization header as a Bearer token to ensure that only authorized requests are processed by the API.

JWT Token Structure

A JWT token consists of three parts:

  1. Header: Contains metadata about the token, such as the algorithm used for signing.
  2. Payload: Contains the claims, which are the statements about an entity (typically, the user) and additional data.
  3. Signature: Ensures the token hasn’t been altered.

Token Example A sample JWT token looks like this:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Generating JWT Tokens in Different Languages

Below are examples of how to generate a JWT token in different programming languages.

  1. Python
import time
import datetime
import jwt

key = """
-----BEGIN RSA PRIVATE KEY-----
[Your Private Key Here]
-----END RSA PRIVATE KEY-----
"""

payload = {
"iat": time.time(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
}

token = jwt.encode(payload=payload, key=key, algorithm="RS256")
print("Bearer", token)
  1. Node.js (JavaScript)
const jwt = require('jsonwebtoken');
const fs = require('fs');

const privateKey = fs.readFileSync('private.key', 'utf8');

const payload = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 15)
};

const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' });
console.log('Bearer', token);
  1. Java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtGenerator {
public static void main(String[] args) {
String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n[Your Private Key Here]\n-----END RSA PRIVATE KEY-----";

long currentTimeMillis = System.currentTimeMillis();

String jwt = Jwts.builder()
.setIssuedAt(new Date(currentTimeMillis))
.setExpiration(new Date(currentTimeMillis + 15 * 60 * 1000)) // 15 minutes
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();

System.out.println("Bearer " + jwt);
}
}
  1. C# (.NET)
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;

class Program
{
static void Main()
{
var rsa = RSA.Create();
rsa.ImportRSAPrivateKey(Convert.FromBase64String("Your Private Key Here"), out _);

var securityKey = new RsaSecurityKey(rsa);
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);

var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
IssuedAt = DateTime.UtcNow,
Expires = DateTime.UtcNow.AddMinutes(15),
SigningCredentials = credentials
};

var token = tokenHandler.CreateToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);

Console.WriteLine("Bearer " + jwt);
}
}

Using the JWT Token

Once generated, the JWT token should be included in the Authorization header for all Order APIs:

Authorization: Bearer <Your_JWT_Token>

Tip: You can also use our Bearer Token Generator to generate tokens with your private key.

Important Notes

  • Private Key Security: Ensure your private key is securely stored and never exposed publicly.
  • Token Expiry: Tokens are valid for 15 minutes. After this period, you will need to generate a new token.
  • Testing: Use tools like Postman to test API requests with the generated JWT tokens.