SyntaxStudy
Sign Up
REST API JWT Authentication in REST APIs
REST API Beginner 1 min read

JWT Authentication in REST APIs

JSON Web Tokens are self-contained credentials consisting of three Base64URL-encoded parts: header (algorithm), payload (claims), and signature. Because the payload is signed, any server with the secret can verify it without a database lookup, making JWTs stateless and horizontally scalable. The standard flow is: client posts credentials to /auth/login, server returns a signed JWT, client sends the JWT in the Authorization: Bearer header on subsequent requests. The server verifies the signature and reads claims (userId, role, exp) directly from the token. Short expiry times (15 min) plus refresh tokens provide a balance of security and usability.
Example
# JWT structure (dot-separated Base64URL parts)
# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9    <- header
# .eyJ1c2VySWQiOiI0MiIsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzE0NTYwMDAwfQ  <- payload
# .SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c  <- signature

# Decoded header:  { "alg": "HS256", "typ": "JWT" }
# Decoded payload: { "userId": "42", "role": "user", "exp": 1714560000 }

# Login endpoint
POST /auth/login HTTP/1.1
Content-Type: application/json
{ "email": "alice@example.com", "password": "secret" }

HTTP/1.1 200 OK
{
  "accessToken":  "eyJ...",
  "refreshToken": "eyJ...",
  "expiresIn":    900
}

# Authenticated request
GET /me HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

# Laravel Sanctum (API token) or jwt-auth (JWT)
// Route::middleware('auth:sanctum')->group(function () {
//   Route::get('/me', fn(Request $r) => $r->user());
//   Route::apiResource('posts', PostController::class);
// });

# Token refresh
POST /auth/refresh HTTP/1.1
Content-Type: application/json
{ "refreshToken": "eyJ..." }

HTTP/1.1 200 OK
{ "accessToken": "eyJ...", "expiresIn": 900 }