What is JWT?
JSON Web Token (JWT) is a compact, URL-safe token format used for securely transmitting information between parties, commonly used for API authentication and authorization.
JWT Explained
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are digitally signed using a secret (HMAC) or public/private key pair (RSA/ECDSA), making them verifiable and trustworthy. A JWT contains three parts: a header (algorithm and token type), a payload (claims/data), and a signature. JWTs are the dominant authentication method for modern APIs because they're stateless—the server doesn't need to store session data. At M3L Software, we implement JWT authentication in virtually every API we build. Our implementations include refresh token rotation, token blacklisting, role-based access control, and secure token storage practices.
Key Features
Common Use Cases
Code Example
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer
import jwt
from datetime import datetime, timedelta
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
app = FastAPI()
security = HTTPBearer()
def create_token(user_id: int) -> str:
payload = {
"sub": user_id,
"exp": datetime.utcnow() + timedelta(hours=24),
"iat": datetime.utcnow()
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def verify_token(credentials = Depends(security)):
try:
payload = jwt.decode(
credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]
)
return payload["sub"]
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
@app.get("/protected")
async def protected_route(user_id: int = Depends(verify_token)):
return {"message": f"Hello user {user_id}"}JWT authentication implementation in FastAPI. The create_token function generates signed tokens with expiration, and verify_token validates them as a dependency that can be injected into any route.
Frequently Asked Questions
Are JWTs secure?
JWTs are secure when implemented correctly: use strong secrets, set short expiration times, use HTTPS only, implement refresh token rotation, and never store sensitive data in the payload (it's base64 encoded, not encrypted).
JWT vs session cookies?
JWTs are stateless and work well for APIs and mobile apps. Session cookies require server-side storage but offer easier revocation. Many modern apps use JWTs for APIs and sessions for web apps.
Where should I store JWTs?
In web apps, store JWTs in httpOnly cookies (most secure) or memory (with refresh tokens). Never store JWTs in localStorage—it's vulnerable to XSS attacks. Mobile apps can use secure storage.
Related Terms
OAuth 2.0
OAuth 2.0 is an authorization framework that enables applications to obtain limited access to user accounts on third-party services, used for 'Login with Google/GitHub' features.
Read moreREST API
A REST API (Representational State Transfer) is an architectural style for building web APIs that uses standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources identified by URLs.
Read moreFastAPI
FastAPI is a modern, high-performance Python web framework for building APIs, known for its speed, automatic documentation, and type-hint-based validation using Pydantic.
Read moreAPI
An Application Programming Interface (API) is a set of rules and protocols that allows different software applications to communicate with each other, enabling data exchange and functionality sharing.
Read moreNeed Help with JWT?
M3L Software specializes in security & authentication. Get expert implementation with founding client pricing (50% off).