0
0
Rest-apiHow-ToBeginner ยท 4 min read

How to Secure REST API: Best Practices and Examples

To secure a REST API, use HTTPS to encrypt data in transit, implement authentication (like OAuth or API keys) to verify users, and apply authorization to control access to resources. Additionally, validate inputs and limit request rates to prevent attacks.
๐Ÿ“

Syntax

Securing a REST API involves these key parts:

  • HTTPS: Use https:// URLs to encrypt data between client and server.
  • Authentication: Verify user identity using tokens like Bearer tokens or API keys.
  • Authorization: Check if the authenticated user has permission to access the requested resource.
  • Input Validation: Ensure data sent to the API is safe and expected.
  • Rate Limiting: Limit how many requests a client can make to prevent abuse.
http
GET /api/resource HTTP/1.1
Host: example.com
Authorization: Bearer <token>

// Server checks:
// 1. Is HTTPS used?
// 2. Is the token valid?
// 3. Does user have access?
// 4. Is input safe?
// 5. Has client exceeded rate limit?
๐Ÿ’ป

Example

This example shows a simple REST API endpoint in Node.js using Express that secures access with an API key and HTTPS enforcement.

javascript
import express from 'express';
const app = express();
const PORT = 3000;

// Middleware to enforce HTTPS
app.use((req, res, next) => {
  if (req.secure || req.headers['x-forwarded-proto'] === 'https') {
    next();
  } else {
    res.status(403).send('Use HTTPS');
  }
});

// Middleware to check API key
app.use((req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  if (apiKey === 'my-secret-key') {
    next();
  } else {
    res.status(401).send('Unauthorized');
  }
});

app.get('/data', (req, res) => {
  res.json({ message: 'Secure data access granted' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Output
Server running on port 3000
โš ๏ธ

Common Pitfalls

Common mistakes when securing REST APIs include:

  • Not using HTTPS, exposing data to interception.
  • Hardcoding or exposing API keys publicly.
  • Skipping authorization checks after authentication.
  • Not validating user input, leading to injection attacks.
  • Failing to limit request rates, allowing denial-of-service attacks.

Always combine multiple security layers for best protection.

javascript
/* Wrong: No HTTPS enforcement and no API key check */
app.get('/data', (req, res) => {
  res.json({ message: 'Unsecured data' });
});

/* Right: Enforce HTTPS and check API key before responding */
app.use((req, res, next) => {
  if (!req.secure && req.headers['x-forwarded-proto'] !== 'https') return res.status(403).send('Use HTTPS');
  next();
});
app.use((req, res, next) => {
  if (req.headers['x-api-key'] !== 'my-secret-key') return res.status(401).send('Unauthorized');
  next();
});
๐Ÿ“Š

Quick Reference

  • Use HTTPS: Always encrypt data in transit.
  • Authenticate: Use tokens or API keys to verify users.
  • Authorize: Check user permissions for each request.
  • Validate Input: Prevent injection and malformed data.
  • Rate Limit: Protect against abuse and DoS attacks.
โœ…

Key Takeaways

Always use HTTPS to protect data between client and server.
Implement authentication and authorization to control access.
Validate all inputs to prevent security vulnerabilities.
Use rate limiting to avoid abuse and denial-of-service attacks.
Never expose secret keys or credentials in your code or public repos.