GÜVENLİK7m READ1 Mayıs 2026

REST API Güvenliği: Temel Kontrol Listesi

Production'a almadan önce kontrol etmen gereken 10 güvenlik maddesi.

REST API'nizi production ortamına almadan önce güvenlik açısından gözden geçirmeniz gereken 10 kritik madde. Bu liste OWASP API Security Top 10'u temel alır ve her teknoloji yığını için geçerlidir.

1. Authentication — Her Endpoint'te Doğrulama

// TYPESCRIPT //
// KÖTÜ — token sadece bazı endpoint'lerde kontrol ediliyor
app.get('/api/users', authMiddleware, userController.list);
app.get('/api/users/:id', userController.getById);  // Auth unutulmuş!
 
// İYİ — route grubu seviyesinde zorunlu auth
const protectedRouter = express.Router();
protectedRouter.use(requireAuth);  // Tüm route'lar için
 
protectedRouter.get('/users', userController.list);
protectedRouter.get('/users/:id', userController.getById);
protectedRouter.patch('/users/:id', userController.update);
 
app.use('/api', protectedRouter);

2. Authorization — Nesne Seviyesinde Yetkilendirme (BOLA/IDOR)

// PYTHON //
# KÖTÜ — sadece giriş yapılmış olması yeterli sayılıyor
@app.route('/api/orders/<int:order_id>')
@login_required
def get_order(order_id: int):
    order = Order.query.get_or_404(order_id)
    return jsonify(order.to_dict())  # Başkasının siparişi!
 
# İYİ — sahiplik kontrolü
@app.route('/api/orders/<int:order_id>')
@login_required
def get_order(order_id: int):
    order = Order.query.filter_by(
        id=order_id,
        user_id=current_user.id  # Sadece kendi siparişleri
    ).first_or_404()
    return jsonify(order.to_dict())

3. Rate Limiting — Brute Force ve DDoS Koruması

// TYPESCRIPT //
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
 
// Giriş endpoint'i — çok sıkı
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,  // 15 dakika
  max: 5,
  message: { error: 'Çok fazla giriş denemesi.' },
  standardHeaders: true,
  store: new RedisStore({ client: redis }),
  skipSuccessfulRequests: true,
});
 
// Genel API — makul limit
const apiLimiter = rateLimit({
  windowMs: 60 * 1000,   // 1 dakika
  max: 100,
  keyGenerator: (req) => req.user?.id ?? req.ip,  // User bazlı
});
 
app.post('/auth/login', loginLimiter, authController.login);
app.use('/api', apiLimiter);

4. Input Validation — Her Girdiye Güvensiz Bak

// PHP //
// Laravel'de Form Request ile validation
class CreateUserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name'     => 'required|string|min:2|max:100|regex:/^[\pL\s]+$/u',
            'email'    => 'required|email:rfc,dns|unique:users,email|max:255',
            'password' => 'required|string|min:12|confirmed|not_in:' . implode(',', $this->commonPasswords()),
            'role'     => 'required|in:user,moderator',  // Admin rolünü giriş sırasında verme!
        ];
    }
}

5. HTTPS ve Güvenlik Başlıkları

// TYPESCRIPT //
// Express — helmet.js ile güvenlik başlıkları
import helmet from 'helmet';
 
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'"],      // 'unsafe-inline' yasak!
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", 'data:', 'https:'],
      connectSrc: ["'self'", 'https://api.yoursite.com'],
    },
  },
  hsts: {
    maxAge: 31_536_000,
    includeSubDomains: true,
    preload: true,
  },
}));

6. Hassas Veri — Ne İfşa Etmediğinizi Bilin

// TYPESCRIPT //
// KÖTÜ — tüm model direkt dönüyor
app.get('/users/:id', async (req, res) => {
  const user = await User.findByPk(req.params.id);
  res.json(user);  // passwordHash, resetToken, internalNotes dahil!
});
 
// İYİ — sadece gerekli alanlar
const UserPublicSchema = z.object({
  id: z.string(),
  name: z.string(),
  avatarUrl: z.string().nullable(),
  createdAt: z.date(),
});
 
app.get('/users/:id', async (req, res) => {
  const user = await User.findByPk(req.params.id);
  if (!user) return res.status(404).json({ error: 'Bulunamadı.' });
  res.json(UserPublicSchema.parse(user));
});

7. SQL Injection — Parametreli Sorgu Zorunlu

// PYTHON //
# Her zaman parametreli sorgu veya ORM kullanın
# ORM (Django, SQLAlchemy, Prisma) otomatik koruması var
 
# Ham SQL gerekiyorsa — parametreli
conn.execute(
    "SELECT * FROM products WHERE category_id = %s AND price < %s",
    (category_id, max_price)  # Parametre ayrı — injection imkansız
)
 
# Hiçbir zaman f-string veya format() kullanmayın
# YASAK: f"SELECT * FROM users WHERE name = '{name}'"

8. Error Handling — Stack Trace Sızdırmayın

// TYPESCRIPT //
// KÖTÜ — stack trace production'da visible
app.use((err: Error, req: Request, res: Response) => {
  res.status(500).json({ error: err.message, stack: err.stack }); // Saldırgana bilgi!
});
 
// İYİ — production'da genel mesaj, loglara detay
app.use((err: AppError, req: Request, res: Response) => {
  logger.error({ err, url: req.url, userId: req.user?.id });
 
  const isProd = process.env.NODE_ENV === 'production';
  res.status(err.statusCode ?? 500).json({
    error: isProd ? 'Bir hata oluştu.' : err.message,
    code: err.code,  // Makine okunabilir hata kodu
  });
});

9. CORS — Origin Whitelist

// TYPESCRIPT //
import cors from 'cors';
 
const allowedOrigins = (process.env.ALLOWED_ORIGINS ?? '').split(',').filter(Boolean);
 
app.use(cors({
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error(`CORS hatası: ${origin} izin listesinde değil.`));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
}));

10. Bağımlılık Güvenliği

Hızlı Kontrol Tablosu

MaddeKontrolDurum
Her endpoint'te authauthMiddleware global
Nesne sahipliği kontrolüuser_id === current_user.id
Rate limitinglogin: 5/15dk, api: 100/dk
Input validationZod / Form Request
HTTPS + güvenlik başlıklarıhelmet / HSTS
Hassas alan filtrelemeDTO / Schema
Parametreli sorguORM veya prepared stmt
Stack trace gizlemeproduction error handler
CORS whitelistenv'den origin listesi
Bağımlılık güvenliğiCI'da npm audit

Sonuç

Bu 10 madde, en yaygın API güvenlik açıklarını kapatır. Bunlar temel; ileri seviyede JWT saldırıları, business logic bypass, timing saldırıları ve API versioning güvenliği gibi konular ayrı bir derse değer.