Series Kubernetes & Helm from scratch · Part 4
Building the Spring Boot auth backend
Build the register, login and MFA backend in Spring Boot 3 with hexagonal architecture, Redis-held codes, JWTs, Flyway and a project-local Java 21 toolchain.
So far we’ve deployed throwaway echo servers. From here on the series deploys a real application, so before we write any more charts we need something worth deploying. In this part we build the backend in apps/backend: a Spring Boot 3.3.5 service on Java 21 that registers users, checks their password, sends a one-time MFA code, and hands back a JWT once the code is right.
Two decisions shape everything below. First, the code follows hexagonal architecture (ports and adapters), so the business rules don’t know or care whether they run against a laptop database or a Kubernetes StatefulSet. Second, every setting that changes between environments is read from an environment variable. That’s what will let a ConfigMap and a Secret configure the same image in part 9.
Project-local tooling
We don’t install Java 21 or Gradle globally. The Gradle wrapper (./gradlew) downloads the pinned Gradle version on first use, and a Java toolchain tells Gradle which JDK to compile with, downloading it if it’s missing. Anyone who clones the repo gets the same versions.
Generate the project with Spring Initializr: Gradle - Kotlin, Java 21, packaging Jar, and unzip it into apps/backend. Initializr includes the wrapper. The series pins Spring Boot 3.3.5; if Initializr no longer offers that release, pick the newest 3.x and change the plugin version afterwards.
apps/backend/settings.gradle.kts:
plugins {
// lets Gradle download a matching JDK when the toolchain asks for one
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "auth-backend"
apps/backend/build.gradle.kts:
plugins {
java
id("org.springframework.boot") version "3.3.5"
id("io.spring.dependency-management") version "1.1.6"
}
group = "com.example"
version = "0.1.0"
java {
toolchain { languageVersion = JavaLanguageVersion.of(21) }
}
repositories { mavenCentral() }
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.flywaydb:flyway-core")
implementation("org.flywaydb:flyway-database-postgresql")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.withType<Test> { useJUnitPlatform() }
The dependency-management plugin lets us leave out version numbers: Spring Boot’s bill of materials picks versions that are tested together. Two lines deserve a note. oauth2-resource-server gives us JWT signing and validation without a third-party library. flyway-database-postgresql is needed because Flyway 10, which Boot 3.3 uses, moved each database’s support into its own module.
Note: the wrapper itself still needs some JVM on the machine to start. The toolchain is what guarantees the code is compiled and run with Java 21, whatever that launcher JVM happens to be.
Ports and adapters
The idea is simple: the middle of the app is plain Java that describes what happens, and everything that talks to the outside world lives at the edges behind interfaces. The middle defines those interfaces, called ports, and the edges provide adapters:
- Inbound ports are the use cases the outside world can trigger: register, log in, verify MFA. The REST controller is an inbound adapter that calls them.
- Outbound ports are what the use cases need from the world: store users, keep a code for five minutes, hash a password, issue a token. JPA, Redis, BCrypt and the JWT encoder are outbound adapters.
The payoff for this series is that swapping Postgres-on-a-laptop for Postgres-in-a-cluster changes configuration, never code, and the use cases can be unit-tested with in-memory fakes.
The package layout under src/main/java/com/example/auth:
domain/ User
application/
port/in/ RegisterUser, Login, VerifyMfa
port/out/ UserRepository, MfaCodeStore, PasswordHasher,
TokenIssuer, MfaCodeSender
AuthService.java implements the in ports using the out ports
adapter/
in/web/ AuthController, request records, error handler
out/persistence/ UserEntity, SpringDataUserRepository, JpaUserRepository
out/redis/ RedisMfaCodeStore
out/security/ BCryptPasswordHasher, JwtTokenIssuer, LoggingMfaCodeSender
config/ SecurityConfig, BeanConfig
Domain and ports
The domain model is a record with no annotations at all:
public record User(UUID id, String email, String passwordHash) {
public static User register(String email, String passwordHash) {
return new User(UUID.randomUUID(), normalise(email), passwordHash);
}
public static String normalise(String email) {
return email.trim().toLowerCase(Locale.ROOT);
}
}
The outbound ports are equally small. Each one names a need, not a technology:
public interface UserRepository { Optional<User> findByEmail(String email); void save(User user); }
public interface MfaCodeStore { void save(UUID userId, String code, Duration ttl); Optional<String> consume(UUID userId); }
public interface PasswordHasher { String hash(String raw); boolean matches(String raw, String hash); }
public interface TokenIssuer { String issue(User user); }
public interface MfaCodeSender { void send(User user, String code); }
The use cases
AuthService implements the three inbound ports. It has no Spring annotations; we’ll wire it up with a @Bean method so the application layer stays framework-free:
public class AuthService implements RegisterUser, Login, VerifyMfa {
private static final Duration MFA_TTL = Duration.ofMinutes(5);
private final SecureRandom random = new SecureRandom();
private final UserRepository users;
private final MfaCodeStore mfaCodes;
private final PasswordHasher hasher;
private final TokenIssuer tokens;
private final MfaCodeSender sender;
// constructor taking all five ports omitted
public void register(String email, String password) {
if (users.findByEmail(User.normalise(email)).isPresent()) throw new EmailTakenException();
users.save(User.register(email, hasher.hash(password)));
}
public void login(String email, String password) {
User user = users.findByEmail(User.normalise(email))
.filter(u -> hasher.matches(password, u.passwordHash()))
.orElseThrow(InvalidCredentialsException::new);
String code = "%06d".formatted(random.nextInt(1_000_000));
mfaCodes.save(user.id(), code, MFA_TTL);
sender.send(user, code);
}
public String verify(String email, String code) {
User user = users.findByEmail(User.normalise(email))
.orElseThrow(InvalidCredentialsException::new);
String expected = mfaCodes.consume(user.id())
.orElseThrow(InvalidCredentialsException::new);
if (!MessageDigest.isEqual(expected.getBytes(UTF_8), code.getBytes(UTF_8))) {
throw new InvalidCredentialsException();
}
return tokens.issue(user);
}
}
The details that matter:
- An unknown email and a wrong password throw the same exception, so the API never reveals which emails are registered.
SecureRandomgenerates the code;Randomis predictable and has no place near authentication.consumereads and deletes in one step, so a code works once. A typo burns it and the user logs in again, which also limits guessing.MessageDigest.isEqualcompares in constant time, so response timing doesn’t leak how many digits matched.
The adapters
The Redis adapter is the whole reason Redis is in the architecture. A key with a TTL is exactly the shape of an MFA code:
@Component
class RedisMfaCodeStore implements MfaCodeStore {
private final StringRedisTemplate redis;
RedisMfaCodeStore(StringRedisTemplate redis) { this.redis = redis; }
public void save(UUID userId, String code, Duration ttl) {
redis.opsForValue().set(key(userId), code, ttl); // SET ... EX 300
}
public Optional<String> consume(UUID userId) {
return Optional.ofNullable(redis.opsForValue().getAndDelete(key(userId))); // GETDEL
}
private static String key(UUID id) { return "mfa:" + id; }
}
The JWT issuer uses Spring Security’s JwtEncoder. Tokens are short-lived and carry the user id as the subject:
@Component
class JwtTokenIssuer implements TokenIssuer {
private final JwtEncoder encoder;
JwtTokenIssuer(JwtEncoder encoder) { this.encoder = encoder; }
public String issue(User user) {
Instant now = Instant.now();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("auth-backend")
.subject(user.id().toString())
.claim("email", user.email())
.issuedAt(now)
.expiresAt(now.plus(Duration.ofMinutes(15)))
.build();
JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();
return encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
}
}
BCryptPasswordHasher wraps Spring’s PasswordEncoder in two one-line methods. LoggingMfaCodeSender logs the code: good enough on a laptop, and when we want email or SMS later it’s one new adapter behind the same port. The JPA adapter maps a UserEntity to and from the domain User, so JPA annotations never leak into the domain.
Schema with Flyway
Hibernate isn’t allowed to touch the schema; Flyway owns it. Put the first migration at src/main/resources/db/migration/V1__create_users.sql:
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(320) NOT NULL UNIQUE,
password_hash VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Flyway runs pending migrations at startup and records them in flyway_schema_history. In Kubernetes that means a new pod migrates the database before it reports ready, which we’ll lean on in part 9.
Security configuration
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**", "/actuator/health/**").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
@Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
@Bean SecretKey jwtKey(@Value("${app.jwt.secret}") String secret) {
return new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
}
@Bean JwtEncoder jwtEncoder(SecretKey key) { return new NimbusJwtEncoder(new ImmutableSecret<>(key)); }
@Bean JwtDecoder jwtDecoder(SecretKey key) { return NimbusJwtDecoder.withSecretKey(key).build(); }
}
- CSRF protection is off because the API holds no cookie session of its own; the browser never talks to it directly. In part 5 the Next.js server keeps the JWT in an HttpOnly cookie and calls this API server to server.
STATELESSstops Spring creating HTTP sessions. Each request proves itself with its token, so any pod can serve any request, which is what lets us run several replicas behind a Service.- The auth endpoints and the health probes are public; everything else needs a valid
Authorization: Bearertoken, checked by the resource server against the same key. - HS256 needs a key of at least 256 bits, so
JWT_SECRETmust be at least 32 bytes.
BeanConfig holds a single @Bean method that constructs AuthService from the five adapters. A small GET /api/me endpoint returning jwt.getSubject() and the email claim gives us something protected to test against.
Configuration from the environment
src/main/resources/application.yml:
spring:
application:
name: auth-backend
datasource:
url: ${DB_URL:jdbc:postgresql://localhost:5432/auth}
username: ${DB_USERNAME:auth}
password: ${DB_PASSWORD:auth}
jpa:
hibernate:
ddl-auto: validate # check entities against the schema, never change it
open-in-view: false
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
app:
jwt:
secret: ${JWT_SECRET} # no default: refuse to start without one
management:
endpoint:
health:
probes:
enabled: true # /actuator/health/liveness and /readiness
endpoints:
web:
exposure:
include: health,info
${NAME:default} reads an environment variable and falls back to the default, so the app runs on a laptop with no setup, and in the cluster the same keys come from a ConfigMap and Secrets. The JWT secret deliberately has no default. The liveness and readiness groups are what our probes will call in part 9.
Run it locally
Start PostgreSQL and Redis in containers with any local container runtime:
docker run -d --name auth-pg -p 5432:5432 \
-e POSTGRES_DB=auth -e POSTGRES_USER=auth -e POSTGRES_PASSWORD=auth postgres:16
docker run -d --name auth-redis -p 6379:6379 redis:7
cd apps/backend
export JWT_SECRET=$(openssl rand -base64 48)
./gradlew bootRun
The first run downloads Gradle and, if needed, JDK 21. In the log you should see Flyway apply V1 and Tomcat start on port 8080. Then walk through the flow:
- Register
curl -i localhost:8080/api/auth/register -H 'Content-Type: application/json' -d '{"email":"ana@example.com","password":"correct-horse-battery"}'returns201. - Log in Same body to
/api/auth/login. It returns202and the backend log prints the six-digit code.docker exec auth-redis redis-cli KEYS 'mfa:*'shows the key, andTTLon it counts down from 300. - Verify
TOKEN=$(curl -s localhost:8080/api/auth/mfa/verify -H 'Content-Type: application/json' -d '{"email":"ana@example.com","code":"123456"}' | jq -r .token), using the code from the log. - Call a protected endpoint
curl -H "Authorization: Bearer $TOKEN" localhost:8080/api/mereturns your id and email. Without the header it's401. - Check the probes
curl localhost:8080/actuator/health/readinessreturns{"status":"UP"}.
Try verifying the same code twice: the second attempt is 401, because GETDEL already removed it.
Takeaways
- Hexagonal architecture keeps the use cases in plain Java; databases, Redis, hashing and tokens are adapters behind ports.
- The Gradle wrapper plus a Java toolchain pins Gradle and JDK 21 per project, with no global installs.
- Redis keys with a TTL are a natural fit for one-time MFA codes, and
GETDELmakes them single-use. - Spring Security’s resource server signs and checks JWTs; a stateless API lets any replica serve any request.
- Flyway owns the schema, and Hibernate only validates against it.
- Every environment-specific setting is an environment variable with a local default, ready for ConfigMaps and Secrets.
Next, in part 5, we build the Next.js frontend that drives register, login and MFA through this API.