☠️
smadi0x86 Playground
  • 💀Welcome to smadi0x86 Playground
    • 🍷Resources
    • 🚬Projects
    • 🎓Certifications
    • 📌Pinned
    • ❓Questions
    • 📞Contact
  • 🏞️Cloud Native
    • Docker
      • Quick Reference
      • Introduction
      • Containers
      • Images
      • Storage & Volumes
      • Security
      • Cheatsheet
    • Git
    • Serverless Framework
    • YAML
  • 🔨Software Engineering
    • System Design
    • Environment Variables
    • JSON Web Tokens
  • 👾Architecture
    • C Language
      • Introduction
      • Calling Conventions
      • GCC Compilation
      • Libraries & Linking
      • I/O
      • Files
      • Pointers
      • Dynamic Memory Allocation
      • Data Types
      • Strings Manipulation
      • Bit Manipulation
      • Pre-processors
      • Macros
      • Type Qualifiers
    • C/C++ Build Systems
      • Fundamentals for Linking
      • Symbolic Linking
      • Cross-Platform Compilation
      • CMake for Building and Linking
      • Shared Libraries
      • Dynamic Linking and Dependency Management
    • Operating Systems
      • OS & Architecture
      • Processes
      • CPU Scheduling
      • Memory Management
  • 🛩️Cyber Warfare
    • Flight Physics
    • Communication
      • PWM & PPM
      • MAVLink
  • 🏴‍☠️Offensive Security
    • Active Directory
      • Introduction
    • Web Attacks
      • Server Side
        • OS Command Injection
        • Information Disclosure
        • Directory Traversal
        • Business Logic
        • Authentication
        • File Upload
        • SSRF
      • Client Side
        • CSRF
        • XSS
    • Recon
      • Active
        • Host discovery
        • Nmap
        • Mass Scan
      • Passive
        • Metadata
      • Web Applications
        • Discovery
        • Subdomains & Directories
        • SSL Certs
        • CMS
        • WAF Detection
      • Firewall Evasion
  • Binary Exploitation
    • Stack Smashing
      • x86
      • x86_64
    • pwntools
      • Processes and Communication
      • Logging and Context
      • Cyclic
      • Packing
      • ELF
      • ROP
  • 😈Advanced Persistent Threat
    • C2
      • Sliver
    • Malware
      • Windows Internals
        • PEB
      • Academy
        • Basics
      • Sektor7
        • Essentials
  • 💌Certifications
    • AWS Certified Cloud Practitioner (CLF-C01)
      • Cloud Foundations
      • Domain 1: Cloud Concepts
      • Domain 2: Security and Compliance
      • Domain 3: Technology
      • Domain 4: Billing and Pricing
    • AWS Certified Solutions Architect - Associate (SAA-C03)
      • Foundation
    • Certified Kubernetes Administrator (CKA)
      • Core Concepts
      • Scheduling
      • Logging & Monitoring
      • Application Lifecycle Management
      • Cluster Maintenance
      • Security
      • Storage
      • Networking
      • Design Kubernetes Cluster
      • Kubernetes The Kubeadm Way
      • Troubleshooting
      • JSONPATH
      • Lightning Lab
      • Mock Exams
      • Killer Shell
    • Certified Kubernetes Security (CKS)
      • Foundation
      • Cluster Setup
      • Cluster Hardening
      • Supply Chain Security
      • Runtime Security
      • System Hardening
      • Killer Shell
    • (KGAC-101) Kong Gateway Foundations
      • Introduction to APIs and API Management
      • Introduction to Kong Gateway
      • Getting Started with Kong Enterprise
      • Getting Started with Kong Konnect
      • Introduction to Kong Plugins
  • 📜Blog Posts
    • Modern Solutions For Preventing Ransomware Attacks
Powered by GitBook
On this page
  • Structure of JWT
  • Setup
  • Creating a JWT
  • Verifying a JWT
  • Using JWT for Authentication
  • Best Practices
  • Libraries for Other Languages
  1. Software Engineering

JSON Web Tokens

JSON Web Tokens (JWT) can be encoded into a URL-friendly string format, which can be signed for authentication and/or encrypted for protection.

Structure of JWT

A JWT typically looks like xxxxx.yyyyy.zzzzz and is divided into:

  • Header: Contains token type and the signing algorithm being used.

  • Payload: Contains the claims which are statements about the entity (typically, the user) and additional data.

  • Signature: To prevent tampering, the header and payload are combined and encrypted.


Setup

Before creating and verifying JWTs, you'll need to install required libraries. Here's how you can do it for a Node.js project:

npm install jsonwebtoken

Creating a JWT

const jwt = require('jsonwebtoken');

// Sample payload
const payload = {
    userId: 12345,
    role: "admin"
};

// Signing the token
const secretKey = "yourSuperSecretKey";
const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });

console.log(token);

Verifying a JWT

const jwt = require('jsonwebtoken');

// Assuming token is received from a client or some source
const receivedToken = "received_token_here";

// Verifying the token
const secretKey = "yourSuperSecretKey";

try {
    const decoded = jwt.verify(receivedToken, secretKey);
    console.log(decoded);
} catch (error) {
    console.error("Invalid token:", error.message);
}

Using JWT for Authentication

A common use case for JWT is authentication. Upon user login, a token is generated and sent to the client. For subsequent requests, the client sends this token back, and the server verifies it.

Generating Token on Login:

app.post('/login', (req, res) => {
    // Validate user credentials (e.g., against a database)
    // ...

    // If valid, generate JWT
    const token = jwt.sign({ userId: user.id }, secretKey, { expiresIn: '1h' });

    res.json({ token });
});

Verifying Token for Protected Routes:

app.get('/protected', (req, res) => {
    const token = req.headers.authorization;

    try {
        const user = jwt.verify(token, secretKey);
        // Continue processing...
    } catch {
        res.status(401).send("Unauthorized");
    }
});

Best Practices

  • Keep it Secret, Keep it Safe: Never expose your secret key. Use environment variables or secret management tools.

  • Short Lifespan: Use short-lived JWTs to reduce potential misuse.

  • Use HTTPS: Always transfer JWTs over a secure layer to prevent Man-In-The-Middle attacks.

  • Handle Expiry Gracefully: Implement mechanisms on the client side to handle token expiry and re-authentication.


Libraries for Other Languages

JWT is supported in many languages. Some popular libraries include:

  • Python: PyJWT

  • Ruby: ruby-jwt

  • Java: java-jwt

PreviousEnvironment VariablesNextC Language

Last updated 1 year ago

🔨
Page cover image