Description
When a servlet copies the request’s Origin into Access-Control-Allow-Origin without checking it, the browser can expose the response to an untrusted site.
Potential impact
If the browser sends the user’s authentication cookie and the server permits credentials, that site may read the user’s API data. CORS does not expose the cookie value itself.
Remediation
- Match the origin’s scheme, host and port against an allow-list before returning it in the response header. Reserve
*for responses intended to be public without credentials. - Add
Vary: Originif the response is cached and the header varies by origin. Allow credentials only where needed, and keep authentication, authorization and CSRF protection in place.
Examples
List the origins your service uses. The excerpts set response headers only. Configure preflight handling and credential permissions separately.
Before
java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class InsecureCORS {
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String origin = request.getHeader("Origin"); // Set from user input
response.setHeader("Access-Control-Allow-Origin", origin); // Unvalidated origin
}
}
After
java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
public class SecureCORS {
private static final Set<String> ALLOWED_ORIGINS = Set.of(
"https://example.com",
"https://sub1.example.com",
"https://sub2.example.com"
);
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String origin = request.getHeader("Origin");
if (origin != null && ALLOWED_ORIGINS.contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
} else {
response.setHeader("Access-Control-Allow-Origin", "https://example.com"); // Default permitted origin
}
}
}
For an unlisted origin, the example returns the fixed value https://example.com. If the requesting origin differs, the browser withholds the response from its script.