Spring cross site scripting XSS issues solution

XSS (Cross-site Scripting) is one of the most common vulnerabilities with a web-application. And, it can be exploited by hackers very easily without using any sophisticated tool.

How does it work?
Most web-applications have forms (text-box etc.) to receive input-data from user. So, a web-application may have a input-text-field to get 'user-id'. The hacker may enter anything in it including "JavaScript". If the hacker enters JavaScript (a malicious code), the server may process it, and then return it. In this case, user-id is not authenticated and it is sent as it is on the error page.

If the user's input data is returned as it is, the java-script code may execute. And, hacker wins!!

I am posting solution for Spring… 

In Spring-MVC, form-tags are used to create jsp page. Spring MVC provides multiple options to encode the html-escape-sequences on server side.

  • At global level, it can be defined in web.xml file. This will be applicable to entire application. All form-tags would refer to this definition. The sample code is shown below:

         <context-param>
            <param-name>defaultHtmlEscape</param-name>
            <param-value>true</param-value>
        </context-param>

  • At page level, it is defined as a tag-declaration. The code is:

          Any form-tag, after the above declaration uses html-escape-sequence-encoding.

          <spring:htmlEscape defaultHtmlEscape="true" />

  • Third option is to define it as attribute for each form-tag. For example, a input-text can be defined as :

          <form:input path="name" htmlEscape="true" />

           Depending upon requirement, it can be implemented as global, page or tag level.

I hope this information helps. Please do post your comments 🙂

12 Replies to “Spring cross site scripting XSS issues solution”

  1. I tried doing the above (all 3), but the special characters are not escaped for me. When I display them, the browser is executing the html/javascript code. Is there additional configuration I have to do?

  2. hey i tried all 3 approaches… in the web.xml, top of the (display, and input pages), and on the input control.

    but it doesn’t seem to escape it. the javascript/html code just executes (browser) when viewing usin ${varname}

    is there other configuration or dependency on the type of view etc? tiles matter?

    this is not a SPAM comment, so don’t just block it!

  3. In my case what was happening is the JavaScript code was executing in the page when enter in the field and submit the form. By using the first option in web.xml it starts escaping

    1. None has worked for me. I am using below instead. Though quite tedious if you you need to escape a lot but it does the job.

      ${fn:escapeXml(myVar)}

Leave a Reply to ravi Cancel reply

Your email address will not be published. Required fields are marked *