Cross Site Scripting (XSS) Prevention

Cross Site Scripting (XSS) attacks are common for web applications. And therefore for security reasons grails 2.3 escape all the html content in ${} expression in GSPs. These configuration setting found in Config.groovy

grails {
views {
gsp {
encoding = 'UTF-8'
htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping
codecs {
expression = 'html' // escapes values inside ${}
scriptlet = 'html' // escapes output from scriptlets in GSPs
taglib = 'none' // escapes output from taglibs
staticparts = 'none' // escapes output from static template parts
}
}
// escapes all not-encoded output at final stage of outputting
// filteringCodecForContentType.'text/html' = 'html'
}
}

This security feature works great but what if you want your html content to be processed, eg. if you have a string like

<strong>Name:</strong> Manish Kumar Bharti<br/><strong>Contact No.:</strong> +91-120-4296782

If you try to render it in GSP then it will be rendered as it is:

<strong>Name:</strong> Manish Kumar Bharti<br/><strong>Contact No.:</strong> +91-120-4296782

To process html content you can use any of the following option:

  • Raw: Raw encode the given html string.
    ${raw(htmlString)}
    

    Note:- Raw is available in tag libraries, controllers and GSP pages.

  • Whole Page Encoding: You can disable this security feature for a full page by adding a page directive like:
    <%@page expressionCodec="none" %>
    
  • Whole Application Encoding: You can disable this feature in Config by setting expression codecs to none like:
    grails {
    views {
    gsp {
    encoding = 'UTF-8'
    htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping
    codecs {
    <b>expression = 'none'</b> // escapes values inside ${}
    scriptlet = 'html' // escapes output from scriptlets in GSPs
    taglib = 'none' // escapes output from taglibs
    staticparts = 'none' // escapes output from static template parts
    }
    }
    // escapes all not-encoded output at final stage of outputting
    // filteringCodecForContentType.'text/html' = 'html'
    }
    }
    

    Note:- When disabling this security feature for a page or whole application be careful, you are opening your application for XSS attacks.

And then your html content will be processed:

Name: Manish Kumar Bharti
Contact No.: +91-120-4296782

Read full documentation here.

Hope this helps 🙂 .