Michel Michel - 3 months ago 6x
AngularJS Question

Should I encode my Json from backend to AngularJs?

I have a .NET backend with a AngularJS frontend.
It all works (no JavaScript executed) when a user enters his name as


The data is sent, as Json, to my backend unencoded, I save the text as entered in the database, and send the text, as Json, unencoded back to the frontend when the data is read.

This all works as said, but watching a security course they advised to encode the Json.

In my case, should I better encode my Json?

This is a part of the Json when saving and loading:



As long as you are setting the content-type to application/json then this content type will not be sniffed by browsers, because it is not "known". Therefore this should be secure against XSS.

There is no need to further encode it.

JSON Hijacking is another vulnerability with GET requests, however it is not an issue in modern browsers.

The only other risk I see is DOM XSS. As long as you are not writing the value "as is" into the DOM, then there is no XSS risk. If you are, then you should HTML encode it, or use JQuery or JavaScript to properly set text/textContent as required so that the browser does not interpret it as script.

Note that the risk here isn't <script>alert('xss')</script>, it would have to be something like <img src=x onload="alert('xss');" /> for it to execute when dynamically added to a document.