使用spring的DelegatingFilterProxy 写xss filter

最近需要写个xss过滤器,将访问网站的所有请求参数都进行xss过滤,过滤的api使用的是antisamy-1.4.4

java代码

 

public class XssFilter implements Filter {

	private static final Logger log = LoggerFactory.getLogger(XssFilter.class);
	
	public static final String POLICY_FILE_LOCATION = "antisamy-slashdot-1.4.4.xml";
	
    private List filterChainDefinitions;
    
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getContextPath();
		String uri = ((HttpServletRequest) request).getRequestURI().replace(path, "");
		Map m = request.getParameterMap();
		if (matchUri(uri)) {
			try {
				m = this.clearRequestPra(request,new HashMap());
			} catch (Exception e) {
				log.info(e.toString());
			}
		}
		
		ParameterRequestWrapper wrapRequest=new ParameterRequestWrapper(((HttpServletRequest) request),m);         
	    chain.doFilter(wrapRequest, response); 
	}
	
	private Map clearRequestPra(ServletRequest request,Map m)
	{
		Map params = request.getParameterMap();
		
	      Set keys = params.keySet();  
	      for (String key : keys) { 
	    	Object value = params.get(key);
	    	if (value instanceof String[]) {
            	value = (String[])value;
            	String[] str = (String[])value; 
            		int i =0;
                	for(String v:(String[])value)
                	{
                		v = this.scan(v);
                		str[i] = new String(v);
                		i++;
                	}
                	m.put(key,str);
	    	}
	    	else
	    	{
	    		m.put(key,value);
	    	}
	      }
		
        return m;
	}
	
	private String scan(String content)
	{
		String cleanHtml = "";
		try{
			Policy policy = Policy.getInstance(POLICY_FILE_LOCATION);
			AntiSamy as = new AntiSamy();
			CleanResults cr = as.scan(content, policy);
			cleanHtml = cr.getCleanHTML();
		}
		catch(Exception e)
		{
			log.info(e.toString());
		}
		return cleanHtml;
	}
	
	private boolean matchUri(String uri)
	{
		for(String pattern:filterChainDefinitions)
		{
			if(Pattern.matches(pattern,uri))
			{
				return true;
			}
				
		}
		return false;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public List getFilterChainDefinitions() {
		return filterChainDefinitions;
	}

	public void setFilterChainDefinitions(List filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
	}
	
}

 application-context-security.xml

 


	
	Security Config
	
	
	
		
			
				
				^/.*
			
			
	

  

 

web.xml 

 

	
	
		xssFilter
		org.springframework.web.filter.DelegatingFilterProxy
	    
	        targetFilterLifecycle
	        true
	    
	    
	        targetBeanName
	        xssFilter
	    	    
	
		
	
		xssFilter
		/*
		REQUEST
		FORWARD
		INCLUDE		
	

 

你可能感兴趣的:(J2EE)