How to prevent JavaScript injection (XSS) when JSTL escapeXml is false

后端 未结 3 1984
春和景丽
春和景丽 2020-12-20 10:52

I have a form that people can add their stuff. However, in that form, if they enter JavaScript instead of only text, they can easily inject whatever they want to do. In orde

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 11:27

    I'd recommend using Jsoup for this. Here's an extract of relevance from its site.

    Sanitize untrusted HTML

    Problem

    You want to allow untrusted users to supply HTML for output on your website (e.g. as comment submission). You need to clean this HTML to avoid cross-site scripting (XSS) attacks.

    Solution

    Use the jsoup HTML Cleaner with a configuration specified by a Whitelist.

    String unsafe = 
          "

    Link

    "; String safe = Jsoup.clean(unsafe, Whitelist.basic()); // now:

    Link

    So, all you basically need to do is the the following during processing the submitted text:

    String text = request.getParameter("text");
    String safe = Jsoup.clean(text, Whitelist.basic());
    // Persist 'safe' in DB instead.
    

    Jsoup offers more advantages than that as well. See also Pros and Cons of HTML parsers in Java.

提交回复
热议问题