Advertisement
Guest User

Oleksandr Loushkin

a guest
Sep 13th, 2015
19,453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.67 KB | None | 0 0
  1. package ua.com.lavi.billing.web.security;
  2.  
  3. import com.google.gson.Gson;
  4. import com.google.gson.reflect.TypeToken;
  5. import org.apache.commons.lang3.RandomStringUtils;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  10. import org.springframework.security.core.context.SecurityContextHolder;
  11. import org.springframework.security.core.userdetails.UserDetails;
  12. import org.springframework.security.core.userdetails.UserDetailsService;
  13. import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
  14. import org.springframework.stereotype.Component;
  15. import org.springframework.web.filter.GenericFilterBean;
  16. import ua.com.lavi.billing.core.utils.IpMACUtils;
  17. import ua.com.lavi.billing.domain.entities.Token;
  18. import ua.com.lavi.billing.service.TokenService;
  19.  
  20. import javax.servlet.FilterChain;
  21. import javax.servlet.ServletException;
  22. import javax.servlet.ServletRequest;
  23. import javax.servlet.ServletResponse;
  24. import javax.servlet.http.HttpServletRequest;
  25. import java.io.IOException;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28.  
  29. @Component
  30. public class RESTAuthenticationTokenProcessingFilter extends GenericFilterBean {
  31.  
  32.     public RESTAuthenticationTokenProcessingFilter(){}
  33.  
  34.     public RESTAuthenticationTokenProcessingFilter(UserDetailsService userService, String restUser) {
  35.         this.userService = userService;
  36.         this.REST_USER = restUser;
  37.     }
  38.  
  39.     @Autowired
  40.     private TokenService tokenService;
  41.     private UserDetailsService userService;
  42.     private String REST_USER;
  43.     private Logger log = LoggerFactory.getLogger(this.getClass());
  44.  
  45.     @Override
  46.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  47.         HttpServletRequest httpRequest = getAsHttpRequest(request);
  48.  
  49.         String authToken = extractAuthTokenFromRequest(httpRequest);
  50.         String[] parts = authToken.split(":");
  51.  
  52.         if (parts.length == 2) {
  53.             String tokenKey = parts[0];
  54.             String tokenSecret = parts[1];
  55.             if (validateTokenKey(tokenKey)) {
  56.                 Token token = tokenService.getTokenByKey(tokenKey);
  57.                 List<String> allowedIPs = new Gson().fromJson(token.getAllowedIP(), new TypeToken<ArrayList<String>>() {}.getType());
  58.                 if (isAllowIP(allowedIPs, request.getRemoteAddr())) {
  59.                     if (token != null) {
  60.                         if (token.getToken().equals(tokenSecret) && token.getExpired().getTime() > System.currentTimeMillis()) {
  61.                             UserDetails userDetails = userService.loadUserByUsername(REST_USER);
  62.                             UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
  63.                             authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
  64.                             SecurityContextHolder.getContext().setAuthentication(authentication);
  65.                             log.info("Authenticated " + token.getKey() + " via IP: " + request.getRemoteAddr());
  66.                             updateLastLogin(token);
  67.                         }
  68.                         else {
  69.                             log.info("Unable to authenticate the token: " + authToken + ". Incorrect secret or token is expired");
  70.                         }
  71.                     }
  72.                 }
  73.                 else {
  74.                     log.info("Unable to authenticate the token: " + authToken + ". IP - " + request.getRemoteAddr() + " is not allowed");
  75.                 }
  76.             }
  77.             else {
  78.                 log.info("Unable to authenticate the token: " + authToken + ". Key is broken");
  79.             }
  80.         }
  81.  
  82.         chain.doFilter(request, response);
  83.     }
  84.  
  85.     private void updateLastLogin(final Token token) {
  86.         Thread updateTokenShread;
  87.         updateTokenShread = new Thread(new Runnable() {
  88.             public void run() {
  89.                 tokenService.updateLastLoginByCurrentDate(token);
  90.             }
  91.         });
  92.         updateTokenShread.setName("RESTTokenThread-" + RandomStringUtils.randomNumeric(4));
  93.         updateTokenShread.start();
  94.  
  95.     }
  96.  
  97.     private boolean isAllowIP(List<String> allowedIps, String remoteAddr) {
  98.         for (String allowedIp : allowedIps) {
  99.             if (validateIP(allowedIp, remoteAddr)) {
  100.                 return true;
  101.             }
  102.         }
  103.         return false;
  104.     }
  105.  
  106.     private boolean validateIP(String allowedIp, String remoteAddr) {
  107.         if (allowedIp.contains("/")) {
  108.             return IpMACUtils.isIpInSubnet(remoteAddr, allowedIp);
  109.         }
  110.         else {
  111.             return allowedIp.equals(remoteAddr);
  112.         }
  113.     }
  114.  
  115.     private boolean validateTokenKey(String tokenKey) {
  116.         String[] parts = tokenKey.split("-");
  117.         return parts.length == 5;
  118.     }
  119.  
  120.     private HttpServletRequest getAsHttpRequest(ServletRequest request) {
  121.         if (!(request instanceof HttpServletRequest)) {
  122.             throw new RuntimeException("Expecting an HTTP request");
  123.         }
  124.  
  125.         return (HttpServletRequest) request;
  126.     }
  127.  
  128.  
  129.     private String extractAuthTokenFromRequest(HttpServletRequest httpRequest) {
  130.         /* Get token from header */
  131.         String authToken = httpRequest.getHeader("X-Auth-Token");
  132.  
  133.         /* If token not found get it from request parameter */
  134.         if (authToken == null) {
  135.             authToken = httpRequest.getParameter("token");
  136.         }
  137.  
  138.         return authToken;
  139.     }
  140.  
  141.  
  142. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement