Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

When you call "eval" method on ScriptEngine passing a String or a Reader, the script is treated as untrusted and so it gets only permissions given to "sandbox" code. This is true for eval ECMAScript builtin function as well. The The evaluated nashorn script evaluated does not inherit permissions of the calling Java code. ! This is because nashorn script engine receives script whose origin URL is unknown to itthe engine! 

So, how can we then grant security permissions for to specific scripts? We may have trusted local scripts - for which we may want to grant more permissions compared to what is given to sandbox scripts.

URLReader

Instead of passing a String or any other Reader to "eval" method, you can pass an instance of jdk.nashorn.api.scripting.URLReader. URLReader constructor accepts a URL. With that, you You can then grant permissions to a specific script by using URL of the script in your security policy file. The following sample code demonstrates the use of URLReader. The following files Main.java, test.js and test.policy are assumed to stored under "D:\test" directory on a Windows machine. You may want to adjust security policy file – if you store these under a different directory (or in a different OS).

...