What is JSON Web Token (JWT)?
Definition
JWT (JSON Web Token) is a compact, URL-safe token format for transmitting claims between parties. It consists of three Base64URL-encoded parts separated by dots: header.payload.signature. The header specifies the algorithm, the payload contains claims, and the signature ensures integrity.
Why It Matters
JWTs are the standard for stateless authentication in web applications and APIs. They eliminate the need for server-side sessions, enable single sign-on (SSO), and work across microservices. Understanding JWT structure is essential for debugging auth issues.
Code Example
import jwt
token = jwt.encode({"sub": "user123", "exp": 1700000000}, "secret", algorithm="HS256")
print(token) # eyJhbGciOi...
Language: python
Frequently Asked Questions
Should I store JWTs in localStorage or cookies?
HttpOnly cookies are more secure because JavaScript cannot access them, preventing XSS attacks from stealing tokens. localStorage is vulnerable to XSS but simpler to implement. For sensitive apps, use HttpOnly cookies with SameSite and Secure flags.