You can use HttpServletRequest to get the IP address of the user. (SpringSecurity developers do the same in their hasIpAddress (...) statement, which is placed in the WebSecurityExpressionRoot class).
For example, you can get HttpServletRequest in two ways:
1) Using RequestContextHolder:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest();
2) Using auto-negotiation:
@Autowired private HttpServletRequest request;
I took it from here .
Then, using the HttpServletRequest, you can get the IP address this way:
String address = request.getRemoteAddr();
And here is how addresses are compared in spring security:
public boolean hasIpAddress(String ipAddress) { return (new IpAddressMatcher(ipAddress).matches(request)); }
And class IpAddressMatcher:
public final class IpAddressMatcher implements RequestMatcher { private final int nMaskBits; private final InetAddress requiredAddress; public IpAddressMatcher(String ipAddress) { if (ipAddress.indexOf('/') > 0) { String[] addressAndMask = StringUtils.split(ipAddress, "/"); ipAddress = addressAndMask[0]; nMaskBits = Integer.parseInt(addressAndMask[1]); } else { nMaskBits = -1; } requiredAddress = parseAddress(ipAddress); } public boolean matches(HttpServletRequest request) { return matches(request.getRemoteAddr()); } public boolean matches(String address) { InetAddress remoteAddress = parseAddress(address); if (!requiredAddress.getClass().equals(remoteAddress.getClass())) { return false; } if (nMaskBits < 0) { return remoteAddress.equals(requiredAddress); } byte[] remAddr = remoteAddress.getAddress(); byte[] reqAddr = requiredAddress.getAddress(); int oddBits = nMaskBits % 8; int nMaskBytes = nMaskBits/8 + (oddBits == 0 ? 0 : 1); byte[] mask = new byte[nMaskBytes]; Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte)0xFF); if (oddBits != 0) { int finalByte = (1 << oddBits) - 1; finalByte <<= 8-oddBits; mask[mask.length - 1] = (byte) finalByte; }
EDIT:
According to related questions here and here, you can add a custom IP address to the session using a custom filter. And then get this information from the session associated with the user, where necessary. For example, you can put IP user information as follows:
public class MonitoringFilter extends GenericFilterBean{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String userIp = httpRequest.getRemoteAddr(); httpRequest.getSession().setAttribute("userIp", userIp);