How to find users' IPs in Spring Security?

后端 未结 3 1857
难免孤独
难免孤独 2020-12-24 15:46

I need to find those user who are logged in our application.
We are using Spring Security and there must be a way to find out users\' IPs.

I think these informa

3条回答
  •  一整个雨季
    2020-12-24 16:11

    I think that the check be achieved by using hasIpAddress http expression

    See section 15.2 Web Security Expressions

    
        
        ...
      
    

    If you want more flexibility, you can implement your own IP address check service, based on IpAddressMatcher:

    
    
    
    
        
    

    bean implementation:

    public class IpCheckService {
        public boolean isValid(HttpServletRequest request) {
            //This  service is a bean so you can inject other dependencies,
                //for example load the white list of IPs from the database 
            IpAddressMatcher matcher = new IpAddressMatcher("192.168.1.0/24");
            
        try {
            return matcher.matches(request);
        } catch (UnsupportedOperationException e) { 
            return false;
        }
        }
    }
    

    update: you can try to get current user IP this way:

        public static String getRequestRemoteAddr(){
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
                       .getRequest(); 
            return request.getRemoteAddr();
    }
    

    update The information about the relation between IP addresses and sessions can only be gathered from the different sources(like listening to AuthenticationSuccessEvent and SessionDestroyedEvent events, implementing a filter or using an AOP interceptor). Spring Security doesn't store such information because it's useless, as IP address has some meaning only while the server is processing a ServletRequest.

    IP address may change(user may be using a proxy), so we can only audit different kinds of events like logging in with some credentials, accessing a service from a different IP, or doing some suspicious activity.

提交回复
热议问题