Security

API Security Best Practices: Protecting Your Data

Practical API security: token and API key authentication, per-object authorization, input validation, parameterized queries, TLS and logging.

By the APIStack team··Updated ·10 min read

Close-up of syntax-highlighted source code on a screen

This article covers the security controls every HTTP API needs: authenticating callers, authorizing each action, validating input, protecting data in transit and at rest, and logging enough to notice an attack. It is written for developers who build and operate APIs. The examples use Node.js with Express, and the principles carry over to any framework.

An API exposes application logic and data directly, without a user interface in between to restrict what a caller can attempt. Every rule has to be enforced on the server, on every request.

Know what goes wrong

The OWASP API Security Top 10 is the standard reference for how APIs are attacked in practice. Its 2023 edition is dominated by authorization failures rather than exotic exploits. The first entry is broken object level authorization, where a caller changes an ID in the request and receives someone else's record. Broken authentication, exposing or accepting object properties the caller should not control, unrestricted resource consumption and security misconfiguration follow.

The sections below address these in turn. If you have limited time, spend it on authorization checks first.

Authenticate every request

Authentication establishes who is calling. For APIs that usually means a bearer token for requests made on behalf of a user, or an API key for server-to-server calls.

Signed tokens

A JSON Web Token (JWT) carries claims about the user and a signature the server can verify without a database lookup. Issue tokens with a short lifetime and with the issuer and audience set.

JavaScript
const jwt = require('jsonwebtoken');

function generateToken(user) {
  return jwt.sign(
    { sub: String(user.id), role: user.role },
    process.env.JWT_SECRET,
    {
      algorithm: 'HS256',
      expiresIn: '15m',
      issuer: 'api.example.com',
      audience: 'api-users'
    }
  );
}

Verification must check the same things the token was issued with. Pin the accepted algorithm and validate the issuer and audience; without these options, a token signed for a different service with the same key would be accepted. A missing or invalid token is a 401, because the caller is not authenticated. 403 is for a caller who is authenticated but not allowed.

JavaScript
function authenticate(req, res, next) {
  const [scheme, token] = (req.get('authorization') || '').split(' ');
  if (scheme !== 'Bearer' || !token) {
    return res.status(401).json({ error: 'Access token required' });
  }

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET, {
      algorithms: ['HS256'],
      issuer: 'api.example.com',
      audience: 'api-users'
    });
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}

A signed token cannot be revoked before it expires, which is why the lifetime is short. Pair it with a longer-lived refresh token that is stored server-side and can be revoked. Claims such as role are a snapshot from the time of issue, so a role change takes effect only when the token is renewed. Keep the signing secret long, random and out of source control. If more than one service needs to verify tokens, use an asymmetric algorithm such as RS256 or ES256 so that verifiers hold only the public key.

API keys

An API key identifies an application rather than a person. Generate keys from a cryptographically secure random source, show the full key to the user once, and store only a hash of it. A fast hash such as SHA-256 is appropriate here because the key is already long and random, unlike a password.

JavaScript
const crypto = require('crypto');

const generateKey = () => crypto.randomBytes(32).toString('base64url');
const hashKey = (key) => crypto.createHash('sha256').update(key).digest('hex');

async function authenticateKey(req, res, next) {
  const key = req.get('x-api-key');
  if (!key) return res.status(401).json({ error: 'API key required' });

  try {
    const { rows } = await pool.query(
      'SELECT id, owner_id FROM api_keys WHERE key_hash = $1 AND revoked_at IS NULL',
      [hashKey(key)]
    );
    if (rows.length === 0) return res.status(401).json({ error: 'Invalid API key' });

    req.apiKey = rows[0];
    next();
  } catch (err) {
    next(err);
  }
}

Accept keys in a header, not in the query string. URLs are written to access logs, browser history and proxy caches, and a key in a URL leaks with them. APIStack follows this convention: every call sends the key in the x-api-key header. Whatever the scheme, let users create several keys and revoke each one independently so that a leaked key can be replaced without downtime.

User passwords need the opposite treatment from API keys. They are short and guessable, so hash them with a deliberately slow algorithm such as Argon2id or bcrypt, never with a plain hash. The OWASP Password Storage Cheat Sheet lists current parameters.

Authorize every action

Authorization decides what an authenticated caller may do. It has two levels, and APIs commonly implement the first and forget the second.

Function-level authorization asks whether this caller may use this endpoint at all. A role check in middleware covers it.

JavaScript
const requireRole = (...roles) => (req, res, next) => {
  if (!roles.includes(req.user.role)) {
    return res.status(403).json({ error: 'Insufficient permissions' });
  }
  next();
};

app.delete('/api/users/:id', authenticate, requireRole('admin'), deleteUser);

Object-level authorization asks whether this caller may touch this particular record. A role check cannot answer that. The reliable approach is to make ownership part of the query, so a record that belongs to someone else is indistinguishable from one that does not exist.

JavaScript
app.get('/api/invoices/:id', authenticate, async (req, res, next) => {
  try {
    const { rows } = await pool.query(
      'SELECT id, amount, status FROM invoices WHERE id = $1 AND owner_id = $2',
      [req.params.id, req.user.sub]
    );
    if (rows.length === 0) return res.status(404).json({ error: 'Invoice not found' });
    res.json(rows[0]);
  } catch (err) {
    next(err);
  }
});

Apply the same check to every route that takes an ID, including updates, deletes and nested resources. Random identifiers such as UUIDs make IDs harder to guess, but they are not a substitute for the check.

Validate input

Treat every part of a request as untrusted: body, query string, path parameters and headers. Validate against a schema that states exactly which fields are allowed, with types, lengths and formats, and reject everything else.

The middleware below uses Joi. The stripUnknown option drops fields that the schema does not list, and the handler then reads the validated value rather than the raw body.

JavaScript
const Joi = require('joi');

const createUserSchema = Joi.object({
  email: Joi.string().email().max(254).required(),
  password: Joi.string().min(12).max(128).required(),
  name: Joi.string().trim().min(1).max(100).required()
});

const validateBody = (schema) => (req, res, next) => {
  const { error, value } = schema.validate(req.body, {
    abortEarly: false,
    stripUnknown: true
  });
  if (error) {
    return res.status(400).json({
      error: 'Validation failed',
      details: error.details.map((detail) => detail.message)
    });
  }
  req.body = value;
  next();
};

app.post('/api/users', validateBody(createUserSchema), createUser);

The schema deliberately has no role field. If a public sign-up endpoint accepts a role from the client, anyone can register as an administrator. This is the mass assignment problem: passing a request body straight into a database model lets the caller set fields you never intended to expose. List the writable fields explicitly, and set privileged ones on the server.

Also limit the size of what you accept. Cap the request body (express.json({ limit: '100kb' })), cap page sizes, and bound array lengths in schemas, so a single request cannot consume disproportionate memory or database time.

Prevent injection with parameterized queries

Validation reduces the attack surface, but it does not prevent SQL injection. Neither does escaping HTML characters in input, which only corrupts stored data. Injection happens when user input is concatenated into a query string and the database parses it as code.

JavaScript
// Vulnerable: the email value becomes part of the SQL text
await pool.query(`SELECT id FROM users WHERE email = '${email}'`);

// Safe: the value is sent separately and is never parsed as SQL
await pool.query('SELECT id FROM users WHERE email = $1', [email]);

Use parameterized queries, or a query builder that produces them, for every statement. The same rule applies to other interpreters: do not build shell commands, NoSQL query objects or file paths from raw input. Escaping for HTML belongs at the point of output, in whatever renders the data in a browser.

Protect data in transit and at rest

Serve the API over HTTPS only. Require TLS 1.2 or later, redirect or refuse plain HTTP, and send the Strict-Transport-Security header so browsers do not downgrade. Credentials sent over plain HTTP should be treated as compromised.

At rest, enable encryption on the database and its backups, which most managed databases offer as a setting. For particularly sensitive fields, encrypt at the application level with keys held in a key management service, so that database access alone does not reveal them. Rotate keys on a schedule and when staff with access leave.

Keep secrets such as signing keys, database passwords and third-party API keys out of the repository. Load them from the environment or a secrets manager, and rotate any secret that has ever been committed.

Return only what the client needs. Select specific columns and build responses from an explicit list of fields, rather than serializing whole database rows and relying on the client to ignore the password hash. In production, error responses should carry a message and a code, not stack traces or SQL errors.

Limit request rates

Without limits, a single client can exhaust your capacity, guess passwords at scale or run up your bill with a downstream provider. Apply rate limits per API key or per user, not only per IP address, and set stricter limits on login, password reset and other endpoints that are expensive or sensitive. Reject excess requests with 429 Too Many Requests and a Retry-After header.

APIStack applies this to its own APIs: each plan has a per-minute limit and a monthly quota, described under rate limits and quotas. For algorithms and implementation details, see Understanding Rate Limiting and How to Handle It.

Log, monitor and test

You cannot respond to an attack you cannot see. Log authentication failures, authorization denials, validation failures and rate-limit rejections, with the caller's identity, the route and a request ID. Alert on patterns such as a burst of 401 responses for one account or a client walking through sequential IDs.

Make security checks part of the normal development cycle. Run a dependency scanner such as npm audit in continuous integration and update vulnerable packages promptly. Write automated tests for authorization: for each endpoint, assert that an unauthenticated request gets 401 and that one user cannot read or change another user's records. Those tests catch the most common and most damaging class of API bug. Periodic penetration tests by someone outside the team find what the tests did not anticipate.

Summary

  • Authorization failures are the most common serious API flaw. Check ownership of the specific record on every request, not just the caller's role.
  • Verify tokens strictly, with a pinned algorithm, issuer, audience and short expiry. Store API keys hashed and accept them in headers, not URLs.
  • Validate input against an allow-list schema, drop unknown fields, and set privileged fields such as roles on the server.
  • Use parameterized queries for all database access. Escaping input does not prevent injection.
  • Serve everything over TLS, keep secrets out of source control, rate limit per caller, and log security events without logging credentials.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading