REST API
Beginner
1 min read
JWT Authentication in REST APIs
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 }