HomeTips and TricksJSON Web Token (JWT): The Complete Guide for Developers to Making Web...

JSON Web Token (JWT): The Complete Guide for Developers to Making Web Apps Safe

Modern developers need to use strong JSON Web Token authentication since web apps are getting more complicated and spread out. JSON Web Token (JWT) is changing the way we verify users across distributed systems by providing a safe, stateless way to do so. You’re in the right place if you’ve been looking into JSON Web Token authentication solutions or are curious about what makes this token-based method so revolutionary for web development today.

What is a JSON Web Token (JWT), exactly?

A JSON Web Token is basically a file type that stores data in a key-value structure. Think of it as a fancy digital envelope that moves data between different portions of your app or even across separate apps.

JWT is beautiful because it is so simple. JWT lets you encode user information directly into a token that the client may carry around instead of keeping session state on the server. This can be a problem when you have several servers. It’s like giving someone a temporary ID card with all the information they need to prove who they are and what they can do.

This is what a common JWT payload might look like:

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

This simple structure has a topic identifier (sub), the user’s name, and the time the token was issued (iat, or issued at time).

The Three-Part Form: Header, Payload, and Signature

There are three sections to every JWT, and they are separated by dots: xxxxx.yyyyy.zzzzz

Header

The header usually has two parts: the type of token (JWT) and the algorithm used to sign it, like HMAC SHA256 or RSA. For instance:

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

Payload

The claims, which are statements about an entity (usually the user), and other information, are in the payload. There are three kinds of claims:

  • Claims that have been registered: Predefined claims like iss (issuer), exp (expiration), and sub (subject)
  • Claims made in public: Claims that should be able to resist collisions
  • Claims made by individuals: Custom claims for sharing information between two people

Signature

The signature is there to make sure that the person who sent the JWT is who they say they are and that the message wasn’t modified along the route. To make it, you take the encoded header, the encoded payload, a secret, and the algorithm that is written in the header.

What does JWT really do in real life?

Here’s a common authentication pipeline that we’ve used many times in real-world applications:

The Login Process

  • Checking the user’s identity: A user sends their login information (username and password) to your server.
  • Checking Credentials: Your server checks these credentials against your database.
  • Making Tokens: When the validation is successful, the server makes a JWT with user information and signs it with a secret key.
  • Delivery of Tokens: This token goes back to the client from the server.
  • Storage for Clients: The client keeps this token, usually in localStorage or in a httpOnly cookie.

Subsequent Requests

Following Requests: For every request that comes after the first one and needs authentication:

  • Token Inclusion: The client puts the JWT in the request header, which is commonly “Authorization: Bearer .”
  • Checking the token: Using its private key, the server checks the token’s signature.
  • Claims Extraction: If the token is legitimate, the server gets user information from it.
  • Processing Requests: The server handles the request with the user’s authenticated context.

The Signing Algorithm: The Key to Your Security

The signing method is where JWT’s security really stands out. There are two main ways to do this:

Symmetric Key (HMAC)

The token issuer and validator both have access to the same secret key. It’s like having a password that everyone can use, which is easy yet needs to be kept safe. These are the algorithms that are most often used:

HS256: HMAC with SHA-256
HS384: HMAC with SHA-384
HS512: HMAC and SHA-512

RSA/ECDSA Asymmetric Key

This employs a pair of public and private keys. The token is signed with the private key and checked with the public key. This is very helpful in distributed systems where many services need to check tokens but shouldn’t be able to get to the signature key.

RS256: SHA-256 plus RSA signature
ES256: SHA-256 ECDSA signature

Example of how to use it in real life

Here’s a real-world example of how we used JWT in a Node.js app recently:

// Token Generation (Login endpoint)
const jwt = require('jsonwebtoken');

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  
  // Validate user credentials (pseudo-code)
  const user = await validateUser(username, password);
  
  if (user) {
    const payload = {
      userId: user.id,
      username: user.username,
      role: user.role,
      exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour expiration
    };
    
    const token = jwt.sign(payload, process.env.JWT_SECRET);
    res.json({ token, user: { id: user.id, username: user.username } });
  } else {
    res.status(401).json({ error: 'Invalid credentials' });
  }
});

// Token Validation (Middleware)
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
  
  if (!token) {
    return res.sendStatus(401);
  }
  
  jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
    if (err) {
      return res.sendStatus(403);
    }
    req.user = decoded;
    next();
  });
};

Common Mistakes and How to Avoid Them

We’ve seen a lot of devs make the same mistakes over the years while working with JWT:

  1. Putting private data in tokens
    Keep in mind that JWT payloads are simply base64 encoded, not encrypted. Anyone may read and understand the information. Don’t ever put passwords, credit card numbers, or other private information in JWT claims.
  2. Not setting expiration dates
    Always put an exp claim in your tokens. For short-term access, we usually configure access tokens to expire in 15 to 30 minutes. For longer-term access, we use refresh tokens.
  3. Problems with client-side storage
    If you save JWTs in localStorage, they are open to XSS attacks. For better security, especially for refresh tokens, think about utilizing httpOnly cookies.
  4. Not Checking Token Claims
    To stop tokens from being used incorrectly, always check not only the signature but additional claims like exp (expiration), iat (issued at), and aud (audience).

JWT vs. Authentication Based on Sessions

We’ve used both methods, and here’s when we think you should use each one:

When to use JWT:

  1. Making microservices or systems that are spread out
  2. Making APIs that don’t need to keep track of state
  3. Setting up single sign-on (SSO) for more than one domain
  4. Making mobile apps where session cookies don’t work well

When to use traditional sessions:

  1. Making simple web apps using server-side rendering
  2. You need the ability to revoke tokens right away.
  3. Handling really sensitive apps where stealing tokens is a big worry

Security Tips We Always Follow

  1. Always use HTTPS: JWT tokens should never be sent over connections that aren’t encrypted.
  2. Use short-lived access tokens with refresh token mechanisms to implement token rotation.
  3. Check All Claims: Don’t only check the signature; also check the assertions about the expiration, audience, and issuer.
  4. Use Strong Secrets: Your JWT secret should be cryptographically strong and changed often.
  5. Put into action: How to Handle Errors Correctly: Don’t tell anyone why token validation didn’t work.
Read More:
- Want to Make Your APIs Faster? Understand API Optimization Techniques
- Golang Interfaces Explained: The Complete Guide for Beginners to Advanced

The Bottom Line

JWT has changed the way we do authentication in modern online apps. Because it doesn’t keep track of state and can securely store user information, it’s a great choice for API authentication and distributed systems.

JWT isn’t a magic bullet, though, like any other technology. It needs to be set up carefully, with the right security measures in place, and you need to know what it can’t do. Knowing when and how to use it well is the key.

If you want to be a better developer, you should learn about JWT. It will help you whether you’re designing your first API or a complicated microservices system. The time and money you spend studying this technology will pay off in the form of more flexible and scalable applications.

It’s not enough to merely choose the right technology for security; you also have to use it correctly and keep it up over time. It’s up to you to use the tools that JWT gives you wisely.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular