Joynex
← Articles

Understanding Web Tokens

Introduction

Web tokens are a way to carry identity or permissions in a string. The most common is JWT (JSON Web Token). Below: what they are and how they’re used in APIs and sessions. Tokens are stateless from the server's perspective: the server verifies the signature and reads the payload without looking up session storage. We'll cover how tokens work, when to use them, and how to avoid common mistakes like storing them insecurely or putting secrets in the payload.

Understanding Web Tokens

What Is Understanding Web Tokens

A token is a string that the client sends (e.g. in the Authorization header or a cookie) so the server knows who the user is or what they’re allowed to do. A JWT has three parts (header.payload.signature) in Base64. The payload holds claims (e.g. user id, expiry); the signature lets the server verify the token wasn’t tampered with. Tokens can be short-lived (minutes) or longer; refresh tokens are used to get new access tokens without logging in again.

Why It Matters

APIs that don’t use cookies need another way to know the client. Tokens are stateless from the server’s perspective: it verifies the signature and reads the payload. That works well for mobile and multi-service setups. Understanding tokens helps you implement and debug auth.

How to Calculate It

Real-Life Example

Login: client sends credentials; server checks them and returns a JWT (and maybe a refresh token). Client stores the JWT (memory or secure storage). On each API request, client sends Authorization: Bearer <token>. Server verifies the signature and expiry, reads user id from the payload, and authorizes the request. When the token expires, client uses the refresh token to get a new one.

Common Mistakes

Storing JWTs in localStorage if you’re worried about XSS (consider httpOnly cookies for web). Not checking expiry or issuer. Putting sensitive data in the payload (it’s Base64, not encrypted). Using a weak secret or leaking the key. Trusting the payload without verifying the signature.

Practical Tips

  • Use a library to create and verify tokens; don’t hand-roll crypto.
  • Keep access tokens short-lived; use refresh tokens for longevity.
  • Don’t put secrets in the JWT payload; assume the payload can be read.
  • Validate signature, expiry, and issuer on every request.
  • For web apps, consider httpOnly cookies for the token to reduce XSS risk.

FAQs

Conclusion

Web tokens (especially JWTs) carry identity or permissions in a verifiable string. Use libraries, keep access tokens short-lived, don’t put secrets in the payload, and validate on every request.