2017-05-05 26 views
0

我試圖將使用戶會話無效無效會話,如果用戶的IP地址的變化(我要強制用戶停留在同一IP地址的會話的整個期間,或者他們需要重新-認證)。我假設Spring Security中有一個特性可以實現這一點,但我似乎無法找到它。如何在客戶端的IP地址更改

是什麼最優雅的方式(通過Spring Security的配置最好)落實這一要求?

回答

2

我找不到任何內置功能在春季安全綁定一個會話的IP,但它很容易使用自定義過濾器來實現:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { 
    boolean chainCompleted = implementEnforcement(request, response); 
    if (!chainCompleted) { 
     filterChain.doFilter(request, response); 
    } 
} 

private boolean implementEnforcement(HttpServletRequest request, HttpServletResponse response) throws IOException { 
    final String key = "enforcement.ip"; 
    HttpSession session = request.getSession(false); 
    if (session != null) { 
     // we have a session 
     String ip = request.getRemoteAddr(); 
     String ipInSession = session.getAttribute(key); 
     if (ipInSession == null) { 
      session.setAttribute(key, ip); 
     } else { 
      if (!ipInSession.equals(ip)) { 
       // JSESSIONID is the same, but IP has changed 
       // invalidate the session because there is a probability that it is 
       // a session hijack 
       session.invalidate(); 
       // a redirection to some page (probably to context root) may be added here 
       return true; 
      } 
     } 
    } 
    return false; 
} 

它會記住用戶的IP地址,然後比較了當前IP記住的一個:如果它不同,會話被破壞。