An API without authentication is like a bank vault with no door. If you put it on the internet, it will be compromised in seconds.
1The Bouncer at the Door
So far, our API endpoints have been completely public. Anyone with the URL can fetch, create, or delete users. This is obviously catastrophic for security. Real-world APIs implement rigorous 'Authentication' and 'Authorization' checks. Think of the API as an exclusive nightclub. The API Gateway is the bouncer. If you show up to the door without a VIP pass, the bouncer will reject your request with a 401 Unauthorized status code.
GET /api/users
// Protected Endpoint
GET /api/users
Headers: { Authorization: 'Bearer vip_pass_123' }
2Authentication vs Authorization
These two terms are often confused, but they mean entirely different things. Authentication is proving WHO you are (e.g., 'I am Alice, here is my password'). Authorization is checking WHAT you are allowed to do (e.g., 'Alice is a standard user, she cannot access the Admin dashboard'). An API must perform both. First, it authenticates the token to ensure you are a valid user. Then, it authorizes the token to ensure you have permission to delete that specific resource.
// "Are you holding a valid ID card?"
// Step 2: Authorization
// "Does your ID card grant access to this VIP room?"
3JSON Web Tokens (JWT)
Because REST APIs are Stateless (they have no memory), the server cannot remember that you logged in 5 minutes ago. To solve this, when you log in, the server generates a cryptographically signed string called a JSON Web Token (JWT) and hands it to you. For every subsequent request, you must attach this JWT inside the HTTP 'Authorization' header. The server mathematically verifies the signature of the token to confirm your identity instantly, without needing to check the database.
fetch("/dashboard", {
headers: {
"Authorization": "Bearer eyJhbGci..."
}
});
4API Keys
JWTs are meant for users (humans) interacting with a frontend. But what if an automated script or a 3rd party backend (like a weather service) needs to access your API? In this case, we use API Keys. An API Key is a long, permanent string generated by the server and given to the developer. The developer embeds this key in their code. It acts as both a username and password rolled into one. If the key leaks, hackers can completely drain the developer's account balance.
fetch("https://api.stripe.com/v1/charges", {
headers: {
"x-api-key": "sk_live_abc123..."
}
});
