Skip to main content
C
CodeUtil

Zero Trust for APIs: Why I Stopped Trusting My Own Network

I learned the hard way that 'inside the firewall' doesn't mean 'safe.' Here's how I rebuilt our API security from the ground up with zero trust.

2025-10-0216 min
Related toolJWT Decoder

Use the tool alongside this guide for hands-on practice.

How I learned to stop trusting my own network

A few years ago, I thought our internal APIs were safe because they sat behind a firewall. Then we found out a compromised developer laptop had been making weird requests for weeks. That was my wake-up call: if you're on our network, you're not automatically trusted anymore.

Zero trust is simple in concept - never trust, always verify. Every single request has to prove who it is and what it's allowed to do. Doesn't matter if you authenticated 5 seconds ago or if you're calling from our own data center. Prove it again.

In this guide, I'll share how I've implemented zero trust for APIs at Šikulovi s.r.o.. I use the JWT Decoder constantly for checking tokens during development, and honestly, it's become my go-to debugging tool for auth issues.

Core principles of zero trust

Zero trust rests on several foundational principles that shape implementation decisions.

Verify explicitly. Authenticate and authorize every request based on all available signals: identity, device, location, time, data sensitivity. Do not assume a user who authenticated once should access everything forever.

Use least privilege access. Grant minimum permissions needed for each task. Prefer just-in-time and just-enough-access over broad, permanent permissions. Reduce standing privileges.

Assume breach. Design systems expecting that adversaries may already have access. Segment systems to contain breaches. Monitor for lateral movement. Make it hard to move from initial access to valuable targets.

These principles apply beyond APIs—to networks, endpoints, and data. But APIs are often the primary attack surface, making zero trust API security essential.

  • Verify explicitly: Authenticate every request
  • Least privilege: Minimum necessary permissions
  • Assume breach: Design for containment
  • Continuous validation: Revalidate throughout session
  • Microsegmentation: Limit lateral movement

Never trust, always verify: implementation

Implementing never trust, always verify requires systematic verification at multiple points in request processing.

Authenticate every request. Stateless APIs should validate authentication tokens on each request. Verify token signatures, check expiration, and validate claims. Use the JWT Decoder to inspect token contents.

Authorize every action. After authentication confirms identity, authorization checks permissions. Use fine-grained policies: can this user perform this action on this resource at this time?

Validate all input. Never trust client-provided data. Validate types, formats, ranges, and business rules. Sanitize data before use. Assume all input is potentially malicious.

Verify request context. Check that requests come from expected sources, use expected protocols, and match expected patterns. Anomalous requests may indicate compromise.

  • Authenticate: Verify identity on every request
  • Authorize: Check permissions for specific actions
  • Validate: Sanitize and verify all input
  • Context: Verify source, protocol, patterns
  • Logging: Record all verification decisions

Identity and access management (IAM)

Strong identity management is the foundation of zero trust. You cannot verify requests without reliable identity.

Use proven authentication protocols. OAuth 2.1 and OpenID Connect provide secure, standardized authentication. Avoid custom protocols—they inevitably have vulnerabilities.

Implement multi-factor authentication (MFA) for human users. Something you know plus something you have dramatically reduces account compromise risk.

Use service accounts with minimal permissions for machine-to-machine communication. Rotate credentials regularly. Avoid long-lived static credentials.

Centralize identity management. A single source of truth for identities enables consistent policy enforcement and simplifies revocation. Federated identity works but complicates the model.

  • OAuth 2.1 / OpenID Connect for authentication
  • MFA for human users
  • Service accounts for machine-to-machine
  • Short-lived credentials with rotation
  • Centralized identity management

API gateway security

API gateways are natural enforcement points for zero trust policies. They see all traffic and can apply consistent security controls.

Terminate TLS at the gateway. Inspect encrypted traffic for threats, then re-encrypt for backend communication. This enables security analysis while maintaining encryption.

Authenticate at the gateway. Validate tokens before requests reach backend services. Reject invalid requests early. This protects backends from handling malformed authentication.

Apply rate limiting and throttling. Limit request rates by user, endpoint, and client. This prevents abuse and limits the impact of compromised credentials.

Implement request validation. Check request size limits, content types, and required headers. Block requests that violate API contracts before they reach business logic.

  • TLS termination with inspection
  • Authentication validation
  • Rate limiting and throttling
  • Request validation
  • Consistent policy enforcement

Request validation and sanitization

Input validation is critical in zero trust—never trust client-provided data regardless of authentication status.

Validate all parameters. Check types, lengths, formats, and allowed values. Use allowlists over denylists. If a field should be a positive integer, verify it is a positive integer.

Sanitize data for context. What is safe for storage may not be safe for display. Sanitize for each use: SQL queries, HTML output, command execution, file paths.

Use the Regex Tester to develop and test validation patterns. Common patterns include email validation, URL validation, and identifier formats. Test patterns against both valid and invalid inputs.

Reject invalid requests completely. Do not attempt to fix malformed input—this may introduce unexpected behavior. Return clear errors so legitimate clients can fix their requests.

  • Validate types, lengths, formats, ranges
  • Use allowlists, not denylists
  • Sanitize for each use context
  • Test patterns with Regex Tester
  • Reject, do not fix, invalid input

Encryption in transit and at rest

Zero trust requires encryption everywhere. Assume network communications are intercepted and stored data is accessed.

Require TLS for all API communication. Do not support HTTP—redirect to HTTPS or reject. Use TLS 1.3 when possible. Configure strong cipher suites.

Encrypt backend communication. Service-to-service traffic should also be encrypted, even inside data centers. Use mutual TLS (mTLS) for service authentication.

Encrypt data at rest. Database encryption, encrypted file systems, and encrypted backups protect against unauthorized access to storage.

Manage encryption keys securely. Use hardware security modules (HSMs) or cloud KMS services. Rotate keys periodically. Separate encryption keys from encrypted data.

  • TLS 1.3 for all external traffic
  • mTLS for service-to-service communication
  • Encrypted databases and storage
  • HSM or cloud KMS for key management
  • Regular key rotation

Continuous monitoring and logging

Zero trust requires visibility into all activity. Detailed logging enables detection and investigation of security events.

Log all authentication and authorization decisions. Record who requested what, when, and whether access was granted. This enables audit trails and anomaly detection.

Monitor for unusual patterns. Impossible travel (user in two locations), unusual access times, bulk data access, or repeated authorization failures may indicate compromise.

Implement real-time alerting. Security events should trigger immediate notifications, not wait for daily log review. Automated response can contain incidents faster.

Retain logs securely. Logs themselves are sensitive—they record who accessed what. Protect logs from tampering and unauthorized access. Follow retention policies.

  • Log all authentication and authorization
  • Detect anomalous patterns
  • Real-time alerting for security events
  • Secure log storage and access
  • Follow retention policies

Implementing with JWT and OAuth

JWTs and OAuth 2.1 are common building blocks for zero trust API authentication.

Validate JWT signatures on every request. Use the JWT Decoder to inspect tokens during development and debugging. Verify the signature algorithm matches your configuration.

Check all relevant claims. Verify issuer (iss), audience (aud), expiration (exp), and any custom claims. Reject tokens with unexpected values.

Use short-lived access tokens. If a token is compromised, short lifetime limits exposure. Five to fifteen minutes is common. Use refresh tokens for longer sessions.

Implement token revocation for high-security scenarios. Reference tokens (opaque strings) can be revoked immediately. JWTs cannot be revoked until expiration—plan token lifetime accordingly.

  • Validate signatures on every request
  • Check issuer, audience, expiration claims
  • Use short-lived access tokens (5-15 minutes)
  • Implement refresh token rotation
  • Consider reference tokens for revocation needs

Zero trust checklist for APIs

Use this checklist to assess and improve your API security posture.

Authentication: Every request is authenticated. Tokens are validated, including signature and claims. MFA is required for human users. Service accounts have minimal permissions.

Authorization: Permissions are checked for every action. Policies are fine-grained (user + action + resource). Least privilege is enforced. No standing admin access.

Validation: All input is validated. Allowlists are used for expected values. Data is sanitized for each use context. Invalid requests are rejected.

Encryption: TLS is required everywhere. Service-to-service uses mTLS. Data at rest is encrypted. Keys are managed securely.

Monitoring: All access is logged. Anomalies trigger alerts. Real-time detection is enabled. Incident response is planned.

  • Authentication: Tokens validated, MFA enabled
  • Authorization: Fine-grained, least privilege
  • Validation: All input checked, sanitized
  • Encryption: TLS everywhere, mTLS internal
  • Monitoring: Detailed logging, real-time alerts

Real-world case studies

Organizations implementing zero trust for APIs have learned valuable lessons.

A financial services company reduced their attack surface by 80% after implementing zero trust. Previously, any authenticated user could access most endpoints. After implementing fine-grained authorization, most users could only access endpoints they actually needed.

A healthcare platform caught a credential theft attack through anomaly detection. When stolen credentials were used from an unusual location, automated alerts triggered investigation within minutes. Zero trust monitoring identified the breach before data exfiltration.

A technology company struggled with mTLS rollout but succeeded incrementally. Starting with the most critical services and expanding gradually reduced risk and allowed teams to build expertise. Full mTLS took 18 months but dramatically improved internal security.

Common challenges include cultural change (developers accustomed to trusting internal traffic), performance overhead (additional validation on every request), and complexity (managing fine-grained policies). Address these through gradual rollout, performance optimization, and tooling investment.

FAQ

What is zero trust security?

It's basically 'trust no one' for APIs. Every request proves its identity, even from inside your network. Sounds paranoid, but after I've seen internal breaches, it makes total sense.

How do I start implementing zero trust for APIs?

Start small. Make sure every request needs a valid token. Then add permission checks per action. Then input validation. Don't try to do everything at once - pick your most critical APIs first.

Does zero trust mean I cannot cache authentication?

Nope, you can still cache. Just be smart about it. I cache validated tokens for a few seconds to avoid hammering the auth server. The point is that each request goes through verification logic, even if it hits a cache.

Is zero trust just about authentication?

Auth is just the start. There's also authorization (can they do this?), input validation (is this data safe?), encryption (everywhere!), and monitoring. It's a whole mindset, not just one feature.

How do I use JWT Decoder for zero trust verification?

I paste my tokens in there to check the claims - issuer, audience, expiration. Also verify the algorithm is solid (RS256, ES256). Just don't paste production tokens with real user data!

What is the performance impact of zero trust?

There's some overhead, yeah. But with smart caching and efficient lookups, it's minimal. Honestly, the security is worth a few milliseconds. I've never had a client complain about auth being slow.

Martin Šikula

Founder of CodeUtil. Web developer building tools I actually use. When I'm not coding, I experiment with productivity techniques (with mixed success).

Related articles

12 min

Secure Password Hashing - MD5, SHA-256, and Beyond

Learn why password hashing matters, why MD5 is broken for security, how SHA-256 differs, and why bcrypt and Argon2 are the right choice for storing passwords. Understand rainbow tables, salting, and modern best practices.

Hash Generatorsecurityhashingpasswordscryptography