Using a razor to set inline javascript variables is good practice / security?

If I wanted to set some javascript variables from my model, would that be safe practice? For instance:

<script type="text/javascript"> var myVariable = '@Model.myVar'; </script> 

Is this a good practice? I can’t think about how best to do this, besides maybe doing hidden input, but this seems like too much work compared to this. I just don’t know if it is vulnerable or if there is something that does not notice, doing it.

+4
source share
3 answers

I think there are a couple of problems with this. Essentially, you are closely linking your javascript to your page or view. I consider myself a solid .NET / C # / MVC developer, but starting with javascript, and this is exactly the type of design that I have pursued until recently. In the past, I would put all kinds of javascript into my views and make heavy use of Razor. It works in the end, but this leads to a very close relationship between your markup and the script, and ultimately creates a complex maintenance environment.

And it is better to use the built-in javascript function calls instead. The difference is subtle, but it will provide a separation of the two areas.

 <script type="text/javascript"> MyFunction('@Model.myVar'); </script> 

You can also enter values ​​in hidden input fields, spaces, etc. through Razor and put them there on your javascript.

+5
source

This should be safe, since the output is encoded in razor by default.

However, if the displayed value is a value that the user can change, you need to make sure that it has been checked (server side) to stop any XSS.

+1
source

You do it perfectly. There will be no vulnerabilities. It does not stop vulnerabilities if they already exist, but this, of course, will no longer add.

0
source

Source: https://habr.com/ru/post/1439892/


All Articles