JWT Parser

JWT Token parsing tool, parse and verify JSON Web Token

Tool Overview: JWT Parser Tool

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact, self-contained way for securely transmitting information between parties. This tool can parse JWT tokens and view their Header, Payload, and Signature contents.

What Is JWT Parser Tool?

JWT Parser Tool parses structured content and highlights key fields for debugging.

How to Use

  1. Paste the content to parse.
  2. The tool extracts and displays fields.
  3. Copy the fields you need.

Common Use Cases

  • Inspect key fields during integration
  • Debug structure and formatting issues
  • Document or demo structured data

❓ FAQ

Q1: Parsing failed?
A: Ensure the input format is complete.

Q2: Missing fields?
A: Check whether the input contains all fields.

Q3: Can it validate signatures?
A: Parsing only shows fields; validation needs keys.

✨ Key Features

  • 🔍 Complete Parsing: Parse JWT Header, Payload, and Signature
  • 📊 Structured Display: Clear display of parsing results in JSON format
  • 🔧 Error Detection: Automatically detect invalid JWT formats
  • 📋 One-click Copy: Parsing results can be directly copied for use
  • 🛡️ Security Tips: Provide JWT security usage recommendations

📖 Usage Examples

Standard JWT Parsing

Input JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Parsing Result:

Header:

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

Payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Signature:

SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

🎯 Application Scenarios

1. API Authentication

Using JWT for user authentication in RESTful APIs:

// Server-side JWT generation
const jwt = require('jsonwebtoken')

// Generate token after successful user login
function generateToken(user) {
  const payload = {
    sub: user.id,
    username: user.username,
    role: user.role,
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour expiration
  }

  return jwt.sign(payload, process.env.JWT_SECRET, {
    algorithm: 'HS256'
  })
}

// Verify token
function verifyToken(token) {
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    return { valid: true, payload: decoded }
  } catch (error) {
    return { valid: false, error: error.message }
  }
}

// Middleware verification
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]

  if (!token) {
    return res.sendStatus(401)
  }

  const result = verifyToken(token)
  if (!result.valid) {
    return res.sendStatus(403)
  }

  req.user = result.payload
  next()
}

2. Microservices Architecture

Passing user information and permissions between microservices:

// Microservice A generates JWT containing user information
const serviceAToken = jwt.sign({
  userId: 123,
  username: 'john_doe',
  permissions: ['read:posts', 'write:posts'],
  serviceId: 'service-a',
  iat: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + 300 // 5 minutes
}, process.env.SERVICE_SECRET)

// Microservice B verifies and uses JWT information
function handleRequest(req, res) {
  const token = req.headers['x-service-token']

  try {
    const decoded = jwt.verify(token, process.env.SERVICE_SECRET)

    // Check permissions
    if (!decoded.permissions.includes('read:posts')) {
      return res.status(403).json({ error: 'Insufficient permissions' })
    }

    // Use user information
    const posts = getPostsByUser(decoded.userId)
    res.json(posts)
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' })
  }
}

3. Frontend Application State Management

Managing user login state in frontend applications:

// JWT handling in Vue.js
import { ref, computed } from 'vue'

export const useAuth = () => {
  const token = ref(localStorage.getItem('jwt_token'))

  // Parse JWT to get user information
  const user = computed(() => {
    if (!token.value) return null

    try {
      const parts = token.value.split('.')
      const payload = JSON.parse(atob(parts[1]))

      // Check if expired
      if (payload.exp * 1000 < Date.now()) {
        logout()
        return null
      }

      return {
        id: payload.sub,
        username: payload.username,
        role: payload.role,
        exp: payload.exp
      }
    } catch (error) {
      console.error('Invalid JWT:', error)
      logout()
      return null
    }
  })

  const isAuthenticated = computed(() => !!user.value)

  const login = (newToken) => {
    token.value = newToken
    localStorage.setItem('jwt_token', newToken)
  }

  const logout = () => {
    token.value = null
    localStorage.removeItem('jwt_token')
  }

  // Auto refresh token
  const refreshToken = async () => {
    try {
      const response = await fetch('/api/refresh', {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      })

      if (response.ok) {
        const { token: newToken } = await response.json()
        login(newToken)
      } else {
        logout()
      }
    } catch (error) {
      console.error('Token refresh failed:', error)
      logout()
    }
  }

  return {
    user,
    isAuthenticated,
    login,
    logout,
    refreshToken
  }
}

4. Mobile Application Authentication

Using JWT for user authentication in mobile applications:

// JWT handling in React Native
import AsyncStorage from '@react-native-async-storage/async-storage'

class AuthService {
  static TOKEN_KEY = 'jwt_token'

  // Save token
  static async saveToken(token) {
    try {
      await AsyncStorage.setItem(this.TOKEN_KEY, token)
    } catch (error) {
      console.error('Failed to save token:', error)
    }
  }

  // Get token
  static async getToken() {
    try {
      return await AsyncStorage.getItem(this.TOKEN_KEY)
    } catch (error) {
      console.error('Failed to get token:', error)
      return null
    }
  }

  // Parse token
  static parseToken(token) {
    if (!token) return null

    try {
      const parts = token.split('.')
      const payload = JSON.parse(atob(parts[1]))

      // Check expiration time
      if (payload.exp * 1000 < Date.now()) {
        this.removeToken()
        return null
      }

      return payload
    } catch (error) {
      console.error('Invalid token format:', error)
      return null
    }
  }

  // Remove token
  static async removeToken() {
    try {
      await AsyncStorage.removeItem(this.TOKEN_KEY)
    } catch (error) {
      console.error('Failed to remove token:', error)
    }
  }

  // Check if logged in
  static async isLoggedIn() {
    const token = await this.getToken()
    const payload = this.parseToken(token)
    return !!payload
  }
}

🔧 Technical Details

JWT Structure

JWT consists of three parts separated by dots (.):

Header:

  • Contains token type (typ) and signing algorithm (alg)
  • Base64URL encoded JSON object
  • Example: {"alg": "HS256", "typ": "JWT"}

Payload:

  • Contains claims information
  • Base64URL encoded JSON object
  • Contains standard claims and custom claims

Signature:

  • Used to verify token integrity
  • Generated using the algorithm specified in the header
  • Prevents token tampering

Complete Format:
header.payload.signature

Standard Claims

JWT defines some standard claims:

Registered Claims:

  • iss: Issuer
  • sub: Subject, usually user ID
  • aud: Audience
  • exp: Expiration Time
  • nbf: Not Before
  • iat: Issued At
  • jti: JWT ID, unique identifier

Public Claims:

  • Can be defined in IANA JWT Registry
  • Or use URI namespace to avoid conflicts

Private Claims:

  • Custom claims for specific applications
  • Such as: username, role, permissions, etc.

Signing Algorithms

JWT supports multiple signing algorithms:

Symmetric Algorithms (HMAC):

  • HS256: HMAC SHA-256
  • HS384: HMAC SHA-384
  • HS512: HMAC SHA-512

Asymmetric Algorithms (RSA):

  • RS256: RSA SHA-256
  • RS384: RSA SHA-384
  • RS512: RSA SHA-512

Elliptic Curve Algorithms (ECDSA):

  • ES256: ECDSA SHA-256
  • ES384: ECDSA SHA-384
  • ES512: ECDSA SHA-512

Selection Recommendations:

  • Monolithic applications: Use HS256
  • Microservices: Use RS256
  • High performance requirements: Use ES256

💡 Usage Tips

  • Expiration Time: Set reasonable token expiration time to balance security and user experience
  • Refresh Mechanism: Implement token refresh mechanism to avoid frequent logins
  • Storage Security: Securely store tokens on the client side to avoid XSS attacks
  • Transmission Security: Always transmit JWT tokens over HTTPS

⚠️ Security Considerations

  • Sensitive Information: Do not store sensitive information in the payload, JWT content is visible
  • Key Security: Properly protect signing keys and rotate them regularly
  • Token Revocation: JWT cannot be revoked, consider using blacklists or short-term tokens
  • Algorithm Verification: Must check the algorithm during verification to prevent algorithm substitution attacks
  • Size Limitations: JWT has size limitations, avoid storing too much information

🚀 Getting Started

  1. Input JWT: Paste the JWT token to be parsed in the input box
  2. Parse: Click the "Parse JWT" button to parse
  3. View Results: View the parsed Header, Payload, and Signature
  4. Copy: Click the "Copy" button to copy the parsing results
  5. Example: Click "Load Example" to view demo data

Tip: This tool only parses JWT on the client side and does not upload your token to the server, ensuring data security.