Prevent Cross Site Scripting Using apex.util.escapreHTML

This is a very common requirement to show the details a user has submitted using JS code.

So, I am going to show the name of the user with a greeting statement in a div.

It's a very simple implementation.

Create a page in APEX with a static region, add following text to the "text" property of the static region.

<div id = 'show_user'></div>

In the above div I want to show "Hello, <user_entered_name>".

Add a text field name "P3_UNTRUSTED_USER" (you can have a different name) to the above static region.

Add a button to the static region, named submit, set action property as "Defined by Dynamic Action".

Create a dynamic action name "Greeting user", event : Click, Selection type: button and Button : Submit. In the true action add an action "Execute Javascript Code" and add following code.

apex.jQuery( "#show_user" ).append( 'Hello '+ $v("P3_UNTRUSTED_NAME") +'!' );

Run the page. Enter your name, it will show the message as expected.

Looks nice, but if a user enters following text, it will execute the JS instead of showing the entered text. The JS code can be anything.

<script>alert('XSS');</script>

I am sure, you don't want this to be happen in your application. So, how to avoid it?

It's pretty easy use apex.util.escapeHTML. So, replace your JS code in the dynamic action as follow.

apex.jQuery( "#show_user" ).append( apex.util.escapeHTML( 'Hello '+ $v("P3_UNTRUSTED_NAME") +'!'  );

Now test with the same inputs, it will print the same text as entered by user.

Happy Coding!!!

Comments