Markus
Markus

Reputation: 4242

HTML and JavaScript and Json = How and when to encode in which order?

my process looks as following:

1.) Server: Encode the content as HTML (=using StringEscapeUtils from apache commons)
2.) Server: Encode the content as JavaScript (=using StringEscapeUtils from apache commons)

3.) Server: Marshall via Jackson JSON library 

4.) Transfer via JSON

5.) Client display via JQuery in the webpage (via the $ajax() call)

Is the process above correct? First HTML encoding then JavaScript encoding?

Do I have to JavaScript encode the content? As far as I can tell, Jackson will correctly encode the Content and Jquery is safe enough to parse even unsecure JavaScript content? So I could drop the JavaScript encoding, is this correct?

Thank you very much! Markus

Upvotes: 0

Views: 381

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120576

What are you embedding?

If what you are embedding is plain text embedded in HTML embedded in JavaScript, e.g. document.write("your text here") then you need to HTML encode before you JS encode.

If what you are embedding is plain text embedded in JavaScript, embedded in HTML, e.g. <button type=button onclick="alert('your text here')"> then you need to do it in the opposite order.

You can think about this as a type problem. You have a string of type string<plain_text> and when you do something like "<a ...>" + myPlainTextString + "</a>" what you are doing is trying to append 3 strings of string<html> and to do that correctly you need to encode/cast the plain text string to string<html> so what you do is "<a ...>" + htmlEncode(myPlainTextString + "</a>".

By this way of reasoning, 3 layers of embedding is just the same as 3 layers of type-casting. Now if only I could convince language type system designers to build in checks for this kind of thing :)

Upvotes: 1

Related Questions