Java · Easy · Free
Debug: why does this equality check fail for user input?
JavaCore JavaStringsFresher
The API compares a request token to a configured secret but authenticated users are rejected even with the correct token.
Java
String expected = System.getenv("API_TOKEN");
String actual = request.getHeader("X-Api-Token");
if (actual == expected) {
return Response.ok();
}
return Response.status(401).build();Root cause
==compares references, not string content.actualandexpectedare different objects even when characters match.- Environment variables and HTTP headers always produce heap strings.
Fix
- Use
Objects.equals(actual, expected)orexpected.equals(actual)with null-safe guard. - Consider constant-time comparison for secrets:
MessageDigest.isEqualon UTF-8 bytes.
Interviewers want you to say reference vs value equality before touching security nuances.