Why Does API Security Matter?
APIs are the backbone of modern applications. Mobile apps, websites, IoT devices and third-party services all communicate through APIs. An insecure API puts your entire system at risk.
More than 40% of the data breaches in 2023 resulted from API security vulnerabilities.
Authentication Methods
1. API Key
It is the simplest method, but it is not sufficient on its own:
# API Key ile istek
curl -H "X-API-Key: abc123xyz789" \
https://api.example.com/users
2. JWT (JSON Web Token)
JWTs are self-contained tokens that carry user identity securely:
// JWT oluşturma (Node.js)
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ userId: 123, role: "admin" },
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);
// JWT doğrulama
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log(decoded.userId); // 123
} catch (err) {
console.log("Token geçersiz!");
}
A JWT consists of three parts:
- Header: The algorithm and token type
- Payload: User data (claims)
- Signature: The signature that verifies token integrity
3. OAuth 2.0
It is an authorization framework that allows third-party applications to access resources on behalf of a user. Features such as "Sign in with Google" use OAuth 2.0.
OAuth 2.0 flow types:
| Flow | Use Case |
|---|---|
| Authorization Code | Web applications (most secure) |
| PKCE | Mobile and SPA applications |
| Client Credentials | Server-to-server communication |
| Device Code | Devices without a screen (TV, IoT) |
API Security Best Practices
Rate Limiting
// Express.js ile rate limiting
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 dakika
max: 100, // Maksimum istek
message: "Çok fazla istek. Lütfen bekleyin."
});
app.use("/api/", limiter);
Input Validation
// Joi ile input validation
const Joi = require("joi");
const userSchema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(8).max(128).required(),
name: Joi.string().min(2).max(100).required()
});
const { error, value } = userSchema.validate(req.body);
if (error) return res.status(400).json({ error: error.details });
Security Checklist
- ✅ Enforce HTTPS
- ✅ Use short lifetimes (1 hour) for JWT tokens
- ✅ Implement a refresh token mechanism
- ✅ Enable rate limiting
- ✅ Validate all inputs
- ✅ Restrict your CORS policy
- ✅ Do not expose sensitive data in API responses
- ✅ Implement logging and monitoring
- ✅ Use API versioning
- ✅ Add security headers (CSP, HSTS, X-Frame-Options)
⚠️ Rule: API security does not mean hiding behind a firewall. Apply the principle of defense in depth at every layer.
