Configuration and secrets in production
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite works on your laptop because its passwords sit in your own files. On a public server those same passwords would be one Git push away from strangers. So where do production settings and secrets live?
Where production config lives
A secret is a value that gives access to something, such as a database password, a JWT signing key or an API key. It is safe only if it lives in one protected place, never in Git or in the image.
The same image runs everywhere, so settings must come from outside it. Spring Boot lets an environment variable override a file value, and the program below models that rule:
Example 1 · Environment variables override file defaults
import java.util.LinkedHashMap;import java.util.Locale;import java.util.Map;
public class RelaxedBindingDemo { // Spring's rule for env var names: dots to underscores, dashes removed, upper case static String envName(String property) { return property.replace(".", "_").replace("-", "").toUpperCase(Locale.ROOT); }
public static void main(String[] args) { Map<String, String> fileDefaults = new LinkedHashMap<>(); fileDefaults.put("server.port", "8080"); fileDefaults.put("shoplite.cors.allowed-origins", "http://localhost:3000"); fileDefaults.put("logging.level.com.shoplite", "DEBUG");
Map<String, String> platformEnv = Map.of( "SHOPLITE_CORS_ALLOWEDORIGINS", "https://shoplite.example", "LOGGING_LEVEL_COM_SHOPLITE", "INFO");
fileDefaults.forEach((property, fileValue) -> { String env = envName(property); String value = platformEnv.getOrDefault(env, fileValue); String from = platformEnv.containsKey(env) ? "env " + env : "file"; System.out.println(property + " = " + value + " (" + from + ")"); }); }}server.port = 8080 (file) shoplite.cors.allowed-origins = https://shoplite.example (env SHOPLITE_CORS_ALLOWEDORIGINS) logging.level.com.shoplite = INFO (env LOGGING_LEVEL_COM_SHOPLITE)
What this code does
envNameapplies Spring Boot's naming rule, soshoplite.cors.allowed-originsbecomesSHOPLITE_CORS_ALLOWEDORIGINS.- This is a simplified model of Boot's property order: a value from the environment wins over the same key in a file, so the platform can change settings without rebuilding the image.
Production settings go into the platform's environment variables, or a shoplite.env file with chmod 600 on your VM. Bigger clouds add a secret store (AWS Secrets Manager, Azure Key Vault, Google Secret Manager) that keeps secrets encrypted and logs who read them.
Two places are always wrong. Git: everyone with the repository, every fork and every old clone has the secret forever. The image: ENV JWT_SECRET=... in a Dockerfile, or a .env copied by COPY . ., is readable by anyone who can pull the image. Spring Boot's relaxed binding maps SHOPLITE_CORS_ALLOWEDORIGINS to shoplite.cors.allowed-origins, and a placeholder such as ${JWT_SECRET} in YAML takes the variable's value.
Predict the output
Which setting wins?
Spring Boot reads both the file and the environment.
Round 1 of 2
What port does the app use?
The prod profile
A profile is a named set of settings that is switched on at start-up. SPRING_PROFILES_ACTIVE=prod loads application-prod.yml on top of application.yml.
The prod profile holds only safe choices and placeholders, never secret values. Here is ShopLite's application-prod.yml:
Example 2 · application-prod.yml: safe choices, no secret values
Runs in: the shoplite-api Spring Boot project (src/main/resources/application-prod.yml)
# prod: the live server. Every secret comes from the platform's environment variables.spring: datasource: url: ${DB_URL} # ...?sslMode=REQUIRED&connectTimeout=10000 username: ${DB_USER} # shoplite_app, never root password: ${DB_PASSWORD} hikari: maximum-pool-size: ${DB_POOL_SIZE:5} flyway: locations: classpath:db/migration # no db/dev-data in production user: ${FLYWAY_USER} password: ${FLYWAY_PASSWORD} jpa: hibernate: ddl-auto: validate web: error: include-stacktrace: never include-exception: falseshoplite: jwt: secret: ${JWT_SECRET} cors: allowed-origins: ${CORS_ALLOWED_ORIGINS}logging: level: root: INFO com.shoplite: INFOmanagement: endpoint: health: show-details: neverspringdoc: api-docs: enabled: false swagger-ui: enabled: falseINFO c.shoplite.ShopliteApiApplication : Starting ShopliteApiApplication v1.2.0 using Java 25 with PID 1 INFO c.shoplite.ShopliteApiApplication : The following 1 profile is active: "prod" ... INFO c.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 8.94 seconds
What this code does
- Every value that is secret or differs per server is a
${...}placeholder; the file itself is safe to commit and to bake into the image. ${DB_POOL_SIZE:5}has a default after the colon;${JWT_SECRET}has none on purpose, so a missing secret stops the start instead of running with a blank key. The Why Containers module's project put a smallproddocument at the end ofapplication.yml; moving it into its ownapplication-prod.ymlkeeps every production rule in one file.
What the prod profile switches:
spring.jpa.hibernate.ddl-auto: validate: Hibernate checks the tables but never changes them; Flyway owns the schema.- No stack traces in responses:
GlobalExceptionHandleranswers a generic 500, andspring.web.error.include-stacktrace: neverkeeps Boot's fallback page safe. INFOlogging forcom.shopliteand the root logger.- No dev extras: no sample data folder in
spring.flyway.locations, Swagger UI off unless you choose to show it,show-details: neveron health.
Find the bug
Find the unsafe production line
Tap the line that must not reach production.
Flyway owns the schema.
Round 1 of 4ConfigCheck: fail fast without printing secrets
Fail fast means the app refuses to start when configuration is missing or unsafe, with one clear message, instead of starting and failing on the first real request.
A fail-fast check prints what it found but masks every secret as ****. The program below checks the required variables, TLS to the database, a non-root user and the JWT key length:
Example 3 · ConfigCheck: required variables, masked output
import java.util.Base64;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;
public class ConfigCheck { static final List<String> REQUIRED = List.of("SPRING_PROFILES_ACTIVE", "DB_URL", "DB_USER", "DB_PASSWORD", "JWT_SECRET", "CORS_ALLOWED_ORIGINS"); static final Set<String> SECRETS = Set.of("DB_PASSWORD", "JWT_SECRET");
static String shown(String name, String value) { if (value == null || value.isBlank()) { return "(missing)"; } return SECRETS.contains(name) ? "****" : value; }
static int check(Map<String, String> env) { int problems = 0; for (String name : REQUIRED) { String value = env.get(name); System.out.println(" " + name + "=" + shown(name, value)); if (value == null || value.isBlank()) { problems++; } } String url = env.getOrDefault("DB_URL", ""); if (!url.isBlank() && !url.contains("sslMode=REQUIRED") && !url.contains("sslMode=VERIFY")) { System.out.println(" problem: DB_URL must require TLS (sslMode=REQUIRED)"); problems++; } if ("root".equals(env.get("DB_USER"))) { System.out.println(" problem: DB_USER must not be root"); problems++; } String secret = env.get("JWT_SECRET"); if (secret != null && !secret.isBlank()) { try { if (Base64.getDecoder().decode(secret).length < 32) { System.out.println(" problem: JWT_SECRET must be at least 32 random bytes"); problems++; } } catch (IllegalArgumentException e) { System.out.println(" problem: JWT_SECRET is not Base64 text"); problems++; } } return problems; }
static void run(String title, Map<String, String> env) { System.out.println(title); int problems = check(env); System.out.println(problems == 0 ? " OK: starting the app" : " FAILED: " + problems + " problem(s), exit code 1"); }
public static void main(String[] args) { if (args.length > 0 && args[0].equals("--env")) { // real use: java ConfigCheck.java --env System.exit(check(System.getenv()) == 0 ? 0 : 1); } Map<String, String> broken = new LinkedHashMap<>(); broken.put("SPRING_PROFILES_ACTIVE", "prod"); broken.put("DB_URL", "jdbc:mysql://db.example.net:3306/shoplite"); broken.put("DB_USER", "root"); broken.put("DB_PASSWORD", "Asha@1234"); broken.put("JWT_SECRET", "c2VjcmV0MTIz"); // Base64 of "secret123" run("Run 1 (copied from a laptop):", broken);
Map<String, String> good = new LinkedHashMap<>(broken); good.put("DB_URL", "jdbc:mysql://db.example.net:3306/shoplite?sslMode=REQUIRED"); good.put("DB_USER", "shoplite_app"); good.put("DB_PASSWORD", "x8Kq2vLw9Rz4Tn6Yp0Jd"); good.put("JWT_SECRET", "q3Vt9kq0yJ8mR2nX5wB7cT1eF4hL6pS8uZ0aD3gK9jM="); good.put("CORS_ALLOWED_ORIGINS", "https://shoplite.example"); run("Run 2 (platform settings):", good); }}Run 1 (copied from a laptop): SPRING_PROFILES_ACTIVE=prod DB_URL=jdbc:mysql://db.example.net:3306/shoplite DB_USER=root DB_PASSWORD=**** JWT_SECRET=**** CORS_ALLOWED_ORIGINS=(missing) problem: DB_URL must require TLS (sslMode=REQUIRED) problem: DB_USER must not be root problem: JWT_SECRET must be at least 32 random bytes FAILED: 4 problem(s), exit code 1 Run 2 (platform settings): SPRING_PROFILES_ACTIVE=prod DB_URL=jdbc:mysql://db.example.net:3306/shoplite?sslMode=REQUIRED DB_USER=shoplite_app DB_PASSWORD=**** JWT_SECRET=**** CORS_ALLOWED_ORIGINS=https://shoplite.example OK: starting the app
What this code does
shownis the only place a value is printed, and it replaces every secret with****, so the check can never leak a password into the platform's logs.c2VjcmV0MTIzis Base64 forsecret123, only 9 bytes, so it fails the 32-byte rule. With--envthe same check reads the realSystem.getenv()and exits with code 1, which stops a container entrypoint or a CI step.- The demo maps make the output repeatable; on a server you would run
java ConfigCheck.java --envwith the platform's variables.
Run a check like this before the app starts, in a container's entrypoint or in CI. In ShopLite itself, JwtProperties and CorsProperties already refuse to start without their values; ConfigCheck shows the same idea on its own.
Strong JWT secrets and rotation
Rotation means replacing a secret with a new one on purpose: on a schedule, when a team member leaves, or after a leak. For ShopLite you set the new JWT_SECRET and redeploy.
ShopLite signs tokens with HS256, which needs a secret of at least 32 bytes of real randomness. Generate it with SecureRandom, never type it yourself:
Example 4 · Generating a 32-byte secret
import java.security.SecureRandom;import java.util.Base64;
public class SecretGenerator { public static void main(String[] args) { byte[] bytes = new byte[32]; // 256 bits for HS256 new SecureRandom().nextBytes(bytes); String secret = Base64.getEncoder().encodeToString(bytes); System.out.println("JWT_SECRET=" + secret); System.out.println("Base64 length: " + secret.length() + " characters for " + bytes.length + " bytes"); }}JWT_SECRET=Zp4mWq8N1rT6vY0bC3eH7jK2sL9xA5dF8gU1iO4nQ2E= Base64 length: 44 characters for 32 bytes
What this code does
SecureRandomgives unpredictable bytes suitable for keys;RandomorMath.random()must never be used for secrets. Your value will differ on every run.- This prints the secret once so you can paste it into the platform's settings. Run it on your own machine and do not save the output in a file inside the repository.
Example 5 · Rotation: tokens signed with the old key stop working
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
public class RotationDemo { static byte[] hmac(String key, String data) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); return mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); }
static String sign(String key, String payload) throws Exception { return payload + "." + Base64.getUrlEncoder().withoutPadding().encodeToString(hmac(key, payload)); }
static boolean verify(String key, String token) throws Exception { int dot = token.lastIndexOf('.'); String payload = token.substring(0, dot); byte[] given = Base64.getUrlDecoder().decode(token.substring(dot + 1)); return MessageDigest.isEqual(given, hmac(key, payload)); }
public static void main(String[] args) throws Exception { String oldKey = "old-secret-demo-only-0123456789ab"; String newKey = "new-secret-demo-only-9876543210zy"; String token = sign(oldKey, "sub=2;roles=CUSTOMER");
System.out.println("Before rotation: " + (verify(oldKey, token) ? "valid" : "invalid -> 401")); System.out.println("After rotation: " + (verify(newKey, token) ? "valid" : "invalid -> 401")); String fresh = sign(newKey, "sub=2;roles=CUSTOMER"); System.out.println("After refresh: " + (verify(newKey, fresh) ? "valid" : "invalid -> 401")); }}Before rotation: valid After rotation: invalid -> 401 After refresh: valid
What this code does
- This is a simplified token (payload and HMAC-SHA256 signature), the same idea as an HS256 JWT. Demo keys are plain text here; real keys are random bytes from
SecureRandom. - After the server switches to
newKey, the old token fails verification and the API answers 401. The client's refresh call gets a token signed with the new key, which verifies again.
Use openssl rand -base64 32 or Java's SecureRandom, and a different secret for dev, test and production.
After a rotation every access token signed with the old key fails verification, so users get a 401 and their client uses its refresh token (stored in the database, not signed with this key) to get a new one. With 15-minute access tokens, the impact is one quiet refresh.
When a secret leaks
A leaked secret is a secret that has reached a place you do not control, such as a pushed commit, a public log or a screenshot. Deleting the file in a new commit does not help, because the old commit still has it.
After a leak the order matters: rotate first, clean up later. The commands below find the commit and replace the secret:
Example 6 · After a leak: rotate first, then clean up
Runs in: a terminal in the shoplite-api repository
# 1. Find where the secret entered the historygit log --oneline -S "JWT_SECRET=" -- .env# 2. Rotate: a new secret in the platform settings, then redeployopenssl rand -base64 32# 3. Stop tracking the file and ignore it from now ongit rm --cached .envecho ".env" >> .gitignoregit commit -m "Stop tracking .env"# 4. Optional, after rotating: remove the file from all historygit filter-repo --invert-paths --path .envgit push --force --alla41c9e2 Add local settings Kq1n6Zr8Vb3Xw0Yt5Hs2Lm7Pd4Fg9Jc1Ae6Ru3Ty8Uo= rm '.env' [main 7d2b0f4] Stop tracking .env 2 files changed, 1 insertion(+), 4 deletions(-)
What this code does
git log -Sfinds the commit that added the text. The old value is now public, so it is replaced in the platform first and the app redeployed before anything else.git filter-repo(a separate tool) rewrites every commit, and the force push replaces the remote history. Copies already made by clones, forks or CI logs still exist, which is why rotation always comes first.
Act in this order: rotate the secret first (new database password, new JWT_SECRET) and redeploy, so the leaked value stops working. Revoke anything issued with it, such as API keys or tokens. Check the database and platform logs for use of the old value. Only then clean the history with git filter-repo and force-push. Rewriting history alone is never enough: forks, clones, CI logs and caches already have the old commit.
Order of execution
A secret leaked: what first?
You pushed the real database password. Put the steps in order.
Next step
Check your understanding
11 quick questions