Java Security Basics Every Backend Developer Needs
The security habits a Java backend needs: validate input, hash passwords, use SecureRandom, protect secrets, restrict deserialization and update dependencies.

Security work for a backend developer is mostly a short list of habits applied everywhere, not clever defenses. The same dozen mistakes appear in incident reports year after year. This post lists the habits that matter and where to read more on each. It sits above OWASP Top Ten for Java developers, which maps them to categories.
1. Treat input as hostile
Everything from outside the process is input: request bodies, headers, query strings, files, messages, even data from your own database that came from users. Bind it to typed objects, validate shape and range and reject what does not fit. See Spring MVC validation.
2. Keep data apart from code
Concatenating input into SQL, shell commands, LDAP filters or templates lets the input change the meaning of the command. Use parameters: prepared statements, ProcessBuilder with an argument list, not a shell string:
new ProcessBuilder("convert", inputPath, outputPath).start(); // arguments are not parsed by a shell3. Encode output for its context
Data going into HTML, JavaScript, CSS or a URL needs encoding for that context. Template engines escape HTML by default; turning that off, or building HTML strings by hand, creates XSS. See preventing XSS.
4. Hash passwords properly
PasswordEncoder encoder = new BCryptPasswordEncoder(); // or Argon2PasswordEncoder
String hash = encoder.encode(rawPassword);
boolean ok = encoder.matches(rawPassword, hash);A password hash must be slow and salted so stolen hashes are expensive to crack. MD5, SHA-1 and a bare SHA-256 are fast and wrong for this job. Spring Security's PasswordEncoder handles salting and lets you upgrade the algorithm later.
5. Use SecureRandom for anything secret
SecureRandom random = new SecureRandom();
byte[] token = new byte[32];
random.nextBytes(token);
String id = Base64.getUrlEncoder().withoutPadding().encodeToString(token);java.util.Random and Math.random() are predictable. Session ids, reset tokens, API keys and nonces all need SecureRandom. A UUID.randomUUID() is generated with SecureRandom and works as an unguessable identifier, though it is not meant as an authentication token.
6. Check authorization on every request
Authentication says who the caller is, and authorization says what they may do. Checking permissions only in the UI means any user can call the API. Check on the server, per resource: the order with id 42 belongs to this user. Broken access control tops the OWASP list for a reason.
7. Protect secrets
No passwords, keys or tokens in source code, properties files in the repository or container images. Read them from environment variables or a secret manager, rotate them and keep them out of logs. A leaked key in a public repository is exploited within minutes by scanners.
8. Use TLS and verify certificates
All traffic over HTTPS, including internal. Never disable certificate verification to make an error go away; fix the trust instead, as in PKIX path building failed.
9. Restrict deserialization
Java native serialization (ObjectInputStream) on untrusted data can execute code through gadget chains in libraries on the classpath. Avoid it for external input. If you cannot, set a deserialization filter with an allow-list:
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter("dev.javahacks.dto.*;!*");JSON libraries have equivalent risks with polymorphic typing; allow-list the types.
10. Parse XML defensively
XML parsers can fetch external entities and exhaust memory. Disable DTDs and external entities:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);11. Keep dependencies current
Most applications are mostly third-party code. Scan the build for known vulnerabilities (OWASP Dependency-Check, GitHub Dependabot, a commercial scanner), and update promptly. The most damaging public Java vulnerabilities of recent years were in libraries.
12. Log carefully
Log security events (failed logins, access denials) and never log secrets, tokens or full card numbers. Strip line breaks from logged user input so it cannot forge entries. Monitor the logs; an unread log protects nothing.
13. Least privilege
The application's database user, its cloud role and the container's user should have only what the application needs. A compromised process then reaches less.
Habits in code: one endpoint done carefully
Principles are easier to remember with an example that applies several of them at once. Take a password reset flow, which touches input handling, randomness, storage of secrets and timing.
Validate the input as a typed object and reject anything that does not fit:
record ResetRequest(@NotBlank @Email @Size(max = 254) String email) {}
record ResetConfirm(
@NotBlank @Size(min = 43, max = 43) String token,
@NotBlank @Size(min = 12, max = 128) String newPassword) {}Generate the token with SecureRandom, send the raw token to the user and store only a hash of it, so a database leak does not hand out working reset links:
@Service
class ResetTokens {
private final SecureRandom random = new SecureRandom();
private final ResetTokenRepository repository;
ResetTokens(ResetTokenRepository repository) {
this.repository = repository;
}
String issue(long userId) {
byte[] bytes = new byte[32];
random.nextBytes(bytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
repository.save(new ResetToken(userId, sha256(token), Instant.now().plus(Duration.ofMinutes(30))));
return token;
}
Optional<Long> redeem(String token) {
return repository.findByHash(sha256(token))
.filter(t -> t.expiresAt().isAfter(Instant.now()))
.map(t -> {
repository.delete(t); // single use
return t.userId();
});
}
private static String sha256(String value) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}A SHA-256 is acceptable here, unlike for passwords, because the token is 256 bits of randomness and cannot be guessed offline. The token expires, it can be used once, and the lookup is by hash, so there is no string comparison on a secret to time. Where you do have to compare two secrets that you hold in memory (an HMAC, an API key), use MessageDigest.isEqual, which takes the same time whether the first byte or the last one differs:
boolean valid = MessageDigest.isEqual(expectedMac, providedMac);Finally, the response must not reveal whether the address exists:
@PostMapping("/password/reset")
ResponseEntity<Void> request(@Valid @RequestBody ResetRequest request) {
users.findByEmail(request.email()).ifPresent(user -> mailer.sendReset(user, tokens.issue(user.id())));
return ResponseEntity.accepted().build(); // same answer whether or not the user exists
}Add a rate limit per address and per IP, and the endpoint stops being a way to enumerate accounts or to flood someone's mailbox.
Outbound calls need the same care
Backends also make requests, and an HTTP client with no timeout is a denial of service waiting for a slow dependency. Set connection and request timeouts, and do not follow redirects blindly:
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://pricing.internal/prices/sku-42"))
.timeout(Duration.ofSeconds(3))
.header("Accept", "application/json")
.build();If the URL comes from a user, validate the host against an allow-list first, as discussed for server-side request forgery in the OWASP post.
A starting checklist for code review
Turn the thirteen habits into questions a reviewer can ask of any pull request that touches a boundary. Does new input pass through validation? Is any string concatenated into SQL, a shell command or HTML? Does a new endpoint check who may call it and which record they may touch? Is a secret read from configuration and kept out of logs? Is a new dependency scanned? Five questions take a minute, and a team that asks them on every review catches most of what the incident reports list.
Making the habits stick
Thirteen habits are easy to agree with and hard to keep, because each one competes with a deadline. The teams that keep them make the safe path the default one. A shared library wraps the password encoder so that nobody types the algorithm name. A base HTTP client has timeouts and redirect limits, so a new integration inherits them. A project template ships with dependency scanning enabled, a secrets scanner in the pre-commit hook and a logging configuration that masks the fields known to be sensitive. When a habit is a line in a template, it survives staff changes, and when it is a paragraph in a wiki, it survives until the next release.
Test the habits as you test features. A unit test that asserts a hash is not the plain password, an integration test that a user cannot read another user's record, and a build step that fails on a known vulnerability each take minutes to write and run on every change. Review pull requests with the checklist above in mind, and when an incident does happen, add the missing check to the list and to the template, so that the same mistake costs the next team nothing.
Where this list stops
It is a starting point. Threat modeling, a secure development lifecycle and penetration testing matter for systems that hold sensitive data. Framework-specific hardening is in posts such as hardening Struts 2. The OWASP Cheat Sheet Series and the Secure Coding Guidelines for Java SE are the primary sources.


