document.body.classList.toggle('menu-open', show); // Add 'menu-open' class to body.

JWT Security Part 6: JWTs in API-centric apps

Jan Masters
Written by Jan Masters
December 19, 2024
Tags – ,

Welcome back, API aficionados and microservices maestros! Today, we’re looking at JWTs in their natural habitat: API-centric apps.

It’s like watching a nature documentary, but instead of wildebeest migrating across the Serengeti, we’re observing tokens traversing the wild landscapes of distributed systems.

Disclaimer: The code examples provided are in JavaScript for illustration purposes only. You might find better examples on StackOverflow or in your preferred programming language’s documentation.

The API-centric apps ecosystem

In the era of microservices, single-page applications (SPAs), and mobile apps, we’re not just dealing with a single application anymore. Instead, imagine a bustling digital metropolis where:

  • Microservices are like specialised departments, each handling specific tasks
  • APIs are the standardised protocols these departments use to communicate
  • Web apps, SPAs and mobile apps are like different terminals where citizens (users) access these services
  • JWTs are the official ID cards that citizens show at each department


For example:

  • The authentication service is like the city’s ID office, issuing official credentials
  • The user profile service manages citizen information
  • The order service handles transactions
  • The notification service manages communications


Each service needs to verify the JWT independently, without calling back to the authentication service for every request. This is why JWTs become particularly valuable in microservices:

  1. Decentralized validation: each service can verify tokens independently
  2. Stateless operation: no need to maintain session state across services
  3. Cross-service communication: one token works across all services (though this needs careful consideration for security)

 

Why JWTs shine in API-land

  • Statelessness: each request carries its own authentication, no need for the API to maintain session state
  • Scalability: authenticate requests without hitting a central database every time
  • Flexibility: one token to rule them all, usable across multiple services and domains

JWTs in API-centric apps: the security tightrope

Using JWTs in API-centric apps is like walking a tightrope. Exhilarating when done right, but one misstep and… well, let’s focus on not misstepping. Let’s not retraumatise the CISOs and personnel responsible for cyber security over the festive season!

Algorithm verification: preventing algorithm manipulation

The “alg” header in JWTs specifies which algorithm was used to sign the token. Without explicit algorithm verification, attackers can exploit algorithm confusion. Here’s a simple example of the right way to verify algorithms:
				
					```javascript
// Secure implementation - always specify your algorithm
jwt.verify(token, SECRET_KEY, {
  algorithms: ['HS256'], // Explicitly specify allowed algorithms
});
```
				
			

CORS: The bouncer at the API club

Cross-Origin Resource Sharing (CORS) is crucial in API-centric apps. It’s like having a bouncer who checks if you’re on the guest list before letting you in. Without proper CORS configuration, your APIs are like a club with no bouncer – anyone can walk in and start a fight.

Token exposure: keep your secrets secret

In API-centric apps, tokens are flying around like confetti at a parade. But remember, these aren’t just pretty pieces of paper – they’re the keys to your kingdom.

  • Use HTTPS: Always. No exceptions. It’s like using an armoured truck instead of a bicycle to transport gold.
  • Minimal payload: Keep your JWTs on a diet. The less info they carry, the less damage if they’re intercepted and successfully cracked. Here’s a contrast:
				
					```javascript
// Good: Minimal payload
{ userId: "123", role: "user" }

// Bad: Oversharing
{ userId: "123", email: "user@email.com", SSN: "123-45-6789",
  creditCard: "4111-1111-1111-1111" }
```
				
			
  • Short lifespans: make your tokens ephemeral. The shorter they live, the smaller the window for misuse.

Microservices maze - who's checking the tokens?

In a microservices architecture, every service needs to be a security expert. It’s like every building in a city having its own security team.
  • Consistent verification: ensure all services verify tokens the same way
  • Centralised Auth service: consider a dedicated authentication service that other services can consult
  • Standard security practices: implement uniform security measures across all services

The token travels: a JWT's journey

Let’s follow a JWT as it travels through one of our API-centric apps:

  1. Born at the authentication service
  2. Safely delivered to the client (via HTTPS, of course)
  3. Stored securely (preferably in HTTP-only cookies)
  4. Attached to an API request header
  5. Scrutinised by the API gateway
  6. Passed along to a microservice
  7. Verified and unpacked by the microservice
  8. Used to personalise the response and do a thing
  9. Sent back with the response
  10. Rinse and repeat until expiration

Best practices and key takeaways

Remember:

  • Secure transmission always (HTTPS is your friend)
  • Verify tokens thoroughly at every step
  • Ensure a sufficient RBAC system is enforced
  • Keep payloads minimal and lifespans short
  • Configure CORS correctly (your API’s bouncer)
  • Consider centralised token verification for consistency
  • Consider API Gateways
  • Log all the things! Make sure that you fully leverage your logs for proactive security

JWTs in API-centric apps: in conclusion

JWTs in API-centric apps are powerful and scalable without the overhead of stateful authentication; however, without proper security considerations and hardening, they can provide an attacker with numerous attack vectors and opportunities.

Stay tuned for our next post, where we’ll explore advanced JWT security measures. It’s like upgrading from a simple lock to a retina-scanning, voice-activated, AI-powered security system. Overkill? Maybe. Cool? Definitely. Better security? Probably, but challenges will likely grow with complexity

Like what you see? Share with a friend!

Jan Masters

This article is written by

Jan Masters

Cyber Security Engineer

In cyber security, there are no magic spells – just knowledge, experience, luck, and a touch of wizardry to turn challenges into solutions.

Cyber Security Engineer Jan – our resident Cyber Wizard (@FlyingPhishy on X, if you’re asking) – is a jack-of-all-trades consultant specialising in infrastructure, cloud, and R&D. He delivers high-quality, holistic penetration tests and drives innovation from within, ensuring our penetration testing services are modern and break the mould.