Skip to content

Commit 2c5fcea

Browse files
committed
Sets correct remote address in WebAuthenticationDetails
1 parent f87b92f commit 2c5fcea

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

web/src/main/java/org/springframework/security/web/authentication/WebAuthenticationDetails.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
*
3030
* @author Ben Alex
3131
* @author Luke Taylor
32+
* @author Lazar Radinović
3233
*/
3334
public class WebAuthenticationDetails implements Serializable {
3435

@@ -44,7 +45,7 @@ public class WebAuthenticationDetails implements Serializable {
4445
* @param request that the authentication request was received from
4546
*/
4647
public WebAuthenticationDetails(HttpServletRequest request) {
47-
this(request.getRemoteAddr(), extractSessionId(request));
48+
this(getClientIp(request), extractSessionId(request));
4849
}
4950

5051
/**
@@ -58,6 +59,20 @@ public WebAuthenticationDetails(String remoteAddress, String sessionId) {
5859
this.sessionId = sessionId;
5960
}
6061

62+
private static String getClientIp(HttpServletRequest request) {
63+
String ip = request.getHeader("X-Forwarded-For");
64+
if (ip != null && !ip.isBlank()) {
65+
// Take the first IP (original client)
66+
return ip.split(",")[0].trim();
67+
}
68+
69+
// Alternative proxy header
70+
ip = request.getHeader("X-Real-IP");
71+
72+
// Fallback to direct client ip
73+
return (ip != null && !ip.isBlank()) ? ip : request.getRemoteAddr();
74+
}
75+
6176
private static String extractSessionId(HttpServletRequest request) {
6277
HttpSession session = request.getSession(false);
6378
return (session != null) ? session.getId() : null;

0 commit comments

Comments
 (0)