Java Applet Permissions

2019-06-23 15:15发布

问题:

I've put together a basic applet where the user selects a file from their hard drive, it reads the first line of this file and passes that off to JavaScript for some additional preprocessing, and then when you click a button it tries to upload that file through an HTTP POST request. I found a very basic open source applet for uploading files that I copied and modified for this last bit.

The trouble is, though, it doesn't quite work. It seems like it's running fine, but then I run into two snags related to permissions. The messages in the Java Console say that the applet had access denied errors on the following two permissions:

java.lang.RuntimePermission setFactory
java.io.FilePermission read

I find this strange, because I thought I had granted permission to the applet already when I built it with the "self-signed" option checked in NetBeans, and then clicked to confirm the little security pop-up in the browser.

Also, the part that I coded myself, where it reads the file and passes the first line on to JavaScript works fine. This is a pretty clear indicator that the applet is able to read from the local file system! The trouble doesn't start until I actually try to start the upload. One thing to note, I suppose, is that the upload process seems to run in a new thread, whereas the rest of it all runs in the main class without creating threads.

I am a total novice to Java and know very little about threads in Java; do I need to pass the permissions onto this new thread somehow? Or something to that effect? Thanks in advance.

回答1:

You probably need to ask the security manager (code, not administrator) for permission to do a privileged operation. For various reasons, it's not generally a good thing for an applet to be able to open a local file, so it's guarded pretty heavily.

The basic key is to call AccessController.doPrivileged() and there's a good little tutorial on it at the Java Ranch FAQ.



回答2:

I had a similar problem which took forever to solve. It turns out applet methods called from JavaScript have no permissions, even if you explicitly grant them in a policy file.

This workaround worked for me (adding commands to a queue which the applet loops through): http://blog.carrythezero.com/?p=5

Make sure you understand the dangers here: Anyone can modify JavaScript on a page and change what's getting fed into the applet. In my case I know the code is never going on a webserver, and the class is unsigned so it will fail unless in the specific location granted by my policy file.



回答3:

It's probably because the JavaScript is unsigned. I strongly suggest not signing code, particularly if you don't know what you are doing. From 6u10 (not on Mac yet) applets can use JNLP including the FileOpenService, so you don't have to sign.