XSS prevention in JSP/Servlet web application

前端 未结 9 1375
自闭症患者
自闭症患者 2020-11-21 13:55

How can I prevent XSS attacks in a JSP/Servlet web application?

9条回答
  •  太阳男子
    2020-11-21 14:29

    I had great luck with OWASP Anti-Samy and an AspectJ advisor on all my Spring Controllers that blocks XSS from getting in.

    public class UserInputSanitizer {
    
        private static Policy policy;
        private static AntiSamy antiSamy;
    
        private static AntiSamy getAntiSamy() throws PolicyException  {
            if (antiSamy == null) {
                policy = getPolicy("evocatus-default");
                antiSamy = new AntiSamy();
            }
            return antiSamy;
    
        }
    
        public static String sanitize(String input) {
            CleanResults cr;
            try {
                cr = getAntiSamy().scan(input, policy);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return cr.getCleanHTML();
        }
    
        private static Policy getPolicy(String name) throws PolicyException {
            Policy policy = 
                Policy.getInstance(Policy.class.getResourceAsStream("/META-INF/antisamy/" + name + ".xml"));
            return policy;
        }
    
    }
    

    You can get the AspectJ advisor from the this stackoverflow post

    I think this is a better approach then c:out particular if you do a lot of javascript.

提交回复
热议问题