Keeping credentials out of code
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A database password typed into a Java file travels with every commit to GitHub and onto every teammate's laptop. Where should a program keep its password instead?
Why a password in source code ends up on GitHub and stays in history
A credential is anything that proves who you are to a system: here, the database user name and password.
A password was committed in Main.java and removed in the next commit. Ask Git whether it still knows it.
Example 1 · A deleted password is still in Git history
Runs in: a Git repository where the password was committed and removed in the next commit
git log --onelinegit show 6b0e285:src/main/java/com/shoplite/app/Main.java$ git log --oneline
4a14add Read password from environment
6b0e285 Connect to MySQL
$ git show 6b0e285:src/main/java/com/shoplite/app/Main.java
String password = "Shop#Lite2026";What this code does
- The newer commit replaced the line with
System.getenv(...), butgit show <old commit>:<file>prints the old version, password included. - On GitHub the same old version is one click away in the file's history, so once pushed, the password must be changed.
Every git commit stores a full copy of the file, and git push sends that copy to GitHub, where bots scan public repositories for passwords within minutes.
Once a password has been pushed, treat it as public: change it in MySQL (ALTER USER ... IDENTIFIED BY ...) and only then clean up the code. Rewriting Git history is slow and easy to get wrong, so the real fix is never committing secrets at all.
Reading settings from environment variables with System.getenv
An environment variable is a name and value that the operating system gives every program started from a terminal or IDE. System.getenv("DB_URL") returns its value, or null when it is not set.
Read the three ShopLite settings with System.getenv and report which ones are missing.
Example 2 · Reading the three settings with System.getenv
public class EnvDemo { public static void main(String[] args) { String[] names = {"DB_URL", "DB_USER", "DB_PASSWORD"}; for (String name : names) { String value = System.getenv(name); if (value == null) { System.out.println(name + " is not set"); } else if (name.endsWith("PASSWORD")) { System.out.println(name + " is set (" + value.length() + " characters)"); } else { System.out.println(name + " = " + value); } } }}DB_URL is not set DB_USER is not set DB_PASSWORD is not set
What this code does
- Run without the variables, every
getenvreturnsnull, so the program saysis not setfor each. After setting them, the same program prints the URL and user and only the length of the password, for exampleDB_PASSWORD is set (13 characters). - The password value is never printed. Even a debug line can end up in a log file or a screenshot.
The code holds only the names DB_URL, DB_USER and DB_PASSWORD; each computer supplies its own values. The finished ShopLite app uses the same three names in every module, so set them once. On macOS and Linux the names are case-sensitive; on Windows they usually are not, so write them exactly the same everywhere. A program only gets the variables that existed when its terminal or IDE started, so open a new terminal, or restart IntelliJ IDEA, after changing them: that is the usual reason getenv still returns null.
Set them before running, for the current window:
- Windows PowerShell:
$env:DB_URL = 'jdbc:mysql://localhost:3306/shoplite', and the same forDB_USERandDB_PASSWORD. Use single quotes, so a$in a password is not treated as a variable.setx DB_URL "..."keeps a value for every new window. - macOS Terminal:
export DB_URL='jdbc:mysql://localhost:3306/shoplite', and the same for the other two. Add the lines to~/.zshrcto keep them for every new window. - IntelliJ IDEA: Run, Edit Configurations, Environment variables, then
DB_URL=...;DB_USER=...;DB_PASSWORD=....
A db.properties file loaded from the classpath
A properties file is a text file of key=value lines; lines starting with # are comments. Java reads it with the Properties class: load reads the lines and getProperty(key) returns a value or null.
Read key=value text with Properties and see how spaces, comments and missing keys behave.
Example 3 · How Properties reads key=value text
import java.io.IOException;import java.io.StringReader;import java.util.Properties;
public class PropertiesDemo { public static void main(String[] args) throws IOException { // The same text you would put in src/main/resources/db.properties String text = """ # ShopLite database settings (this file is NOT committed) db.url = jdbc:mysql://localhost:3306/shoplite db.user=shoplite_app\s db.password=Shop#Lite2026 """;
Properties props = new Properties(); props.load(new StringReader(text));
System.out.println("db.url = " + props.getProperty("db.url")); System.out.println("db.password = " + props.getProperty("db.password")); System.out.println("db.pool = " + props.getProperty("db.pool")); System.out.println("db.pool = " + props.getProperty("db.pool", "5") + " (with a default)");
String user = props.getProperty("db.user"); System.out.println("db.user = [" + user + "] length " + user.length()); System.out.println("trimmed = [" + user.trim() + "] length " + user.trim().length()); }}db.url = jdbc:mysql://localhost:3306/shoplite db.password = Shop#Lite2026 db.pool = null db.pool = 5 (with a default) db.user = [shoplite_app ] length 13 trimmed = [shoplite_app] length 12
What this code does
- Spaces around
=are removed and the#line is skipped, but#inside a value (Shop#Lite2026) is kept. A missing key givesnull, or the default you pass as the second argument. - The
\sat the end of thedb.userline is a real trailing space.Propertieskeeps it, so the value has 13 characters instead of 12 until you calltrim().
Example 4 · src/main/java/com/shoplite/app/ReadDbProperties.java
Runs in: the shoplite-console Maven project
package com.shoplite.app;
import java.io.IOException;import java.io.InputStream;import java.util.Properties;
public class ReadDbProperties { public static void main(String[] args) throws IOException { Properties props = new Properties(); try (InputStream in = ReadDbProperties.class.getClassLoader() .getResourceAsStream("db.properties")) { if (in == null) { System.out.println("db.properties is not on the classpath."); System.out.println("Copy db.properties.example to src/main/resources/db.properties."); return; } props.load(in); } System.out.println("db.url = " + props.getProperty("db.url")); System.out.println("db.user = " + props.getProperty("db.user")); System.out.println("db.password = " + (props.getProperty("db.password") == null ? "missing" : "******")); }}$ mvn -q compile exec:java -Dexec.mainClass=com.shoplite.app.ReadDbProperties db.properties is not on the classpath. Copy db.properties.example to src/main/resources/db.properties. (after copying the file and filling in the values) $ mvn -q compile exec:java -Dexec.mainClass=com.shoplite.app.ReadDbProperties db.url = jdbc:mysql://localhost:3306/shoplite db.user = shoplite_app db.password = ******
What this code does
getResourceAsStream("db.properties")looks in the classpath, which Maven fills fromsrc/main/resources. The first run had no file, so the stream wasnulland the program said what to do.- Run Maven again after adding the file (
compilecopies it). The password is shown only as******.
Put ShopLite's file at src/main/resources/db.properties. Maven copies everything in that folder onto the classpath, so the program finds it with getClassLoader().getResourceAsStream("db.properties") on any computer, without a full path. When the file is missing, that call returns null; check for it, or load throws a NullPointerException.
Maven also copies the file into target/classes and into the JAR it builds, so never hand that JAR to anyone else.
Fix the error
Fix the hidden space
The value in db.properties ends with a space. Pick the line that fixes the login.
db.properties has db.user=shoplite_app with a trailing space.
Error
Access denied for user 'shoplite_app '@'localhost' (using password: YES)
Committing db.properties.example and ignoring the real file
.gitignore is a text file that lists paths Git must never add, such as src/main/resources/db.properties. It only stops files Git is not already tracking.
Ignore the real settings file, then ask Git to prove it is ignored.
Example 5 · .gitignore and checking it
Runs in: the shoplite-console Git repository
# .gitignore (project root)target/.idea/*.iml# Local secrets: never commitsrc/main/resources/db.properties.env# then, in the terminal:git status --shortgit check-ignore -v src/main/resources/db.properties$ git status --short ?? .gitignore ?? db.properties.example $ git check-ignore -v src/main/resources/db.properties .gitignore:6:src/main/resources/db.properties src/main/resources/db.properties
What this code does
git statuslists the new.gitignoreanddb.properties.example, but notsrc/main/resources/db.properties, although that file exists.git check-ignore -vnames line 6 of.gitignoreas the rule that hides it. If it prints nothing, the file is not ignored.
Teammates still need to know which settings exist, so commit db.properties.example at the project root, with fake values such as db.password=change-me. A new teammate copies it to src/main/resources/db.properties and fills in their own values.
If db.properties was committed once, .gitignore is too late: run git rm --cached src/main/resources/db.properties and commit, so Git stops tracking it. Then change the password, because the old commit still has it.
Failing fast with a clear message when a setting is missing
Fail fast means checking every required setting at startup and stopping at once with a message that says exactly what is missing and how to fix it.
Combine both sources in one DatabaseConfig: an environment variable wins, then the file, and a missing setting stops the program.
Example 6 · DatabaseConfig: environment first, file second, fail fast
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Properties;
class StartupException extends RuntimeException { StartupException(String message) { super(message); }}
record DatabaseConfig(String url, String user, String password) { private static final String PREFIX = "jdbc:mysql://";
static DatabaseConfig from(Map<String, String> env, Properties file) { List<String> missing = new ArrayList<>(); String url = pick(env, "DB_URL", file, "db.url", missing); String user = pick(env, "DB_USER", file, "db.user", missing); String password = pick(env, "DB_PASSWORD", file, "db.password", missing); if (!missing.isEmpty()) { throw new StartupException("Missing database settings: " + String.join(", ", missing) + ". Set the environment variables or copy db.properties.example to db.properties."); } if (!url.startsWith(PREFIX)) { throw new StartupException("The database URL must start with " + PREFIX + " but was: " + url); } return new DatabaseConfig(url, user, password); }
private static String pick(Map<String, String> env, String envName, Properties file, String key, List<String> missing) { String value = env.get(envName); if (value == null || value.isBlank()) { value = file.getProperty(key); } if (value == null || value.isBlank()) { missing.add(envName + " (or " + key + ")"); return null; } return value.trim(); }
@Override public String toString() { return "DatabaseConfig[url=" + url + ", user=" + user + ", password=******]"; }}
public class DatabaseConfigDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/shoplite"; Map<String, String> env = Map.of( "DB_URL", url, "DB_USER", "shoplite_app", "DB_PASSWORD", "Shop#Lite2026"); System.out.println("1. " + DatabaseConfig.from(env, new Properties()));
Properties file = new Properties(); file.setProperty("db.url", url); file.setProperty("db.user", "shoplite_app"); file.setProperty("db.password", "Shop#Lite2026"); Map<String, String> override = Map.of("DB_URL", url.replace("localhost", "db.college.lan")); System.out.println("2. " + DatabaseConfig.from(override, file));
Map<String, String> partial = Map.of("DB_URL", url); try { DatabaseConfig.from(partial, new Properties()); } catch (StartupException e) { System.out.println("3. " + e.getMessage()); }
Map<String, String> typo = Map.of( "DB_URL", url.replace("mysql:", "mysql"), "DB_USER", "shoplite_app", "DB_PASSWORD", "Shop#Lite2026"); try { DatabaseConfig.from(typo, new Properties()); } catch (StartupException e) { System.out.println("4. " + e.getMessage()); } }}1. DatabaseConfig[url=jdbc:mysql://localhost:3306/shoplite, user=shoplite_app, password=******] 2. DatabaseConfig[url=jdbc:mysql://db.college.lan:3306/shoplite, user=shoplite_app, password=******] 3. Missing database settings: DB_USER (or db.user), DB_PASSWORD (or db.password). Set the environment variables or copy db.properties.example to db.properties. 4. The database URL must start with jdbc:mysql:// but was: jdbc:mysql//localhost:3306/shoplite
What this code does
- Run 1 takes all three settings from the environment. Run 2 takes user and password from the file, but the environment's URL wins over the file's.
toStringnever shows the password. - Run 3 lists both missing settings in one message, with the variable and the file key for each. Run 4 catches a mistyped URL (
jdbc:mysql//..., made withreplace) at startup, before any connection is tried. - The mini project copies this record into
com.shoplite.configand adds aload()method that passesSystem.getenv()and the realdb.properties.
Without failing fast, a missing password shows up later as a confusing Access denied for user 'asha'@'localhost' (using password: NO). Collect all missing names and report them together, so the user fixes everything in one go. Give secrets no default value, ever.
A config object must also never print the password. A record's automatic toString prints every field, so DatabaseConfig overrides it and logging the config at startup stays safe.
Predict the output
Which value wins?
Environment first, file second. Pick what each program prints.
Round 1 of 3
The environment has a user and so does the file.
Next step
Check your understanding
12 quick questions