How do I safely “eval” user code in a webpage?

后端 未结 5 781
难免孤独
难免孤独 2020-12-16 01:19

I\'m working on a webapp to teach programming concepts. Webpages have some text about a programming concept, then let the user type in javascript code into a text editor wi

5条回答
  •  有刺的猬
    2020-12-16 02:09

    It can't be done. Browsers offer no API to web pages to restrict what sort of code can be executed within a given context.

    However, that might not matter. If you don't use any cookies whatsoever on your website, then executing arbitrary Javascript may not be a problem. After all, if there is no concept of authentication, then there's no problem with forging requests. Additionally, if you can confirm that the user meant to execute the script he/she sent, then you should also be protected from attackers, e.g., if you will only run script typed onto the page and never script submitted via GET or POST data, or if you include some kind of unique token with those requests to confirm that the request originated with your website.

    Still, the answer to the core question is that it pretty much is that it can't be done, and that user input can never be trusted. Sorry :/

提交回复
热议问题