Securing REST APIs with JSON Web Tokens in Spring Security

When Australian fintech teams in Sydney and Melbourne expose payment endpoints to mobile clients, the conversation quickly turns away from session cookies and toward stateless authentication. JSON Web Tokens offer a compact, URL-safe way to carry verified identity across services, which is exactly what distributed systems spanning Brisbane, Perth, and Adelaide demand.

This guide walks through a practical implementation pattern for protecting REST endpoints with tokens, paying attention to Australian regulatory realities. The Office of the Australian Information Commissioner expects reasonable safeguards under the Privacy Act, and many local teams align their defences with guidance from the Australian Cyber Security Centre. Token-based security fits comfortably within that mindset.

Why Token-Based Authentication Matters for Modern APIs

REST APIs serve browsers, native apps, and partner systems that often span multiple time zones, including Australian Eastern Standard Time and Australian Western Standard Time. Session-based authentication forces servers to keep state, complicating horizontal scaling. JSON Web Tokens move that state into the client, removing the need for sticky sessions.

A well-designed token carries signed claims about the caller, so downstream services verify identity without calling back to an authorisation server. This delegation model underpins OAuth2 and OpenID Connect, and integrates with Spring Security through familiar filters. For teams serving Australian customers on platforms like Afterpay, this decoupling simplifies audit trails.

Core Concepts Behind JSON Web Tokens

A JSON Web Token is a base64url-encoded string made of three parts: a header describing the algorithm, a payload of claims such as subject and expiration, and a signature produced with a secret or private key. The signature prevents tampering, and choosing between HMAC SHA-256 and asymmetric algorithms like RSA or ECDSA shapes how your services share verification material.

Claims deserve careful thought because every byte in the payload is readable by anyone holding the token. Sensitive data such as tax file numbers must stay out of the payload, even though Australian privacy obligations make that obvious. Standard claims like iss, aud, exp, and iat give you strong defaults, while private claims carry application-specific roles such as ROLE_REPORTER or ROLE_ADMIN.

Setting Up Spring Security Dependencies

Start by adding spring-boot-starter-security and spring-boot-starter-oauth2-resource-server to your build. The resource server starter pulls in the JWT decoder machinery, including support for JWK endpoints and built-in validators. A library such as io.jsonwebtoken:jjwt remains useful when you need to mint tokens yourself rather than delegate to an external identity provider.

Keep your signing key outside source control, ideally in a managed secret store like AWS Secrets Manager or HashiCorp Vault, and rotate it on a schedule that matches the sensitivity of the data behind the API. Australian teams bound by long-term support commitments usually pair this with Java 17 or 21 and a Spring Boot version that matches their maintenance window.

Building a JWT Authentication Filter

The filter sits in the Spring Security chain, extracts the Authorization: Bearer header, validates the token, and populates the SecurityContext with an authenticated principal. Customising this step is the cleanest way to translate JWT claims into Spring authorities, especially when roles arrive as a custom claim rather than the default scope field.

Inside the filter, catch signature exceptions, expiration, and malformed tokens separately so error responses stay informative without leaking details. Returning a structured 401 with WWW-Authenticate headers keeps behaviour predictable. For projects that generate supporting documents on demand, the same application may rely on a PDF generation workflow after authentication succeeds.

Configuring the Security Filter Chain

Disable CSRF for stateless endpoints, set session policy to STATELESS, and permit only the login and health routes while requiring authentication everywhere else. Keep CORS configuration aligned with the origins you actually serve, since broad wildcards weaken protection for browsers but are irrelevant for server-to-server traffic common in Australian banking integrations.

Method-level annotations such as @PreAuthorize("hasRole('ADMIN')") then express fine-grained rules on controllers, and they read well in code reviews. Pair them with a global exception handler that translates AccessDeniedException and AuthenticationException into consistent JSON responses, which is the format most local API consumers expect.

Managing Token Lifecycles and Verification Hardening

Short-lived access tokens limit damage if one leaks, while refresh tokens keep users logged in without re-authentication. Store refresh tokens hashed and revoke them on logout to match Australian expectations around account takeover protection on services like CommBank or NAB. Token rotation invalidates each previous refresh token, and signing algorithm choice affects performance, key distribution, and compliance posture.

Approach Secret Distribution Verification Cost Best For
HMAC SHA-256 Single shared secret Very low Single-service deployments, internal APIs
RSA or ECDSA Public key via JWK URL Moderate Multi-service systems, federated identity
Symmetric with rotation Versioned secrets Low to moderate Regulated workloads needing frequent rotation
Remote introspection Centralised authorisation server Higher per request High-trust enterprise integrations

Beyond algorithm choice, enforce clock skew tolerance, validate the issuer and audience on every request, and log failed verifications with enough context for review. Australian teams bound by the Notifiable Data Breaches scheme benefit from logs that show token IDs, request origins, and the protected resource.

Practical Recommendations for Production-Ready Token Security

Treat the following checklist as a baseline. Each item reflects a control that has repeatedly proven its worth in production deployments across Australian enterprises and government agencies, and they align with broader security frameworks reviewed during quarterly audits.

Re-review these controls each quarter as your services evolve, since new threats and updated Spring Security releases often introduce stronger defaults worth adopting.