I am writing a simple applet (my first) to retrieve the most recent status from a twitter account. This works fine when running from javaw.exe launched from within eclipse. However, when run from a browser I get the error:
java.security.AccessControlException: access denied (java.net.SocketPermission twitter.com:80 connect, resolve)
Any advice on how to avoid this?
The call:
private void updateStatus() {
try {
Twitter client = new Twitter("user", "pw");
Status status = client.getStatus();
addItem(status.toString());
}
catch (Throwable t) {
addItem(t.getMessage());
}
}
The connection to the client is succeeding. It is the getStatus() call which throws开发者_开发技巧 the exception. I notice that eclipse adds "-Djava.security.policy=java.policy.applet" to javaw.exe, not sure if this has anything to do with why it works from eclipse and not from within a browser. Frustratingly, I tried to run the same javaw.exe command directly with the same CL parameters and PATH as eclipse uses successfully. However, when I run it directly javaw.exe exits immediately. jtwitter is a simple wrapper on the Twitter API.
Browser applets are running in a sandbox with lower security permissions. Certain operations are not allowed, such as certain GUI operations (to prevent e.g. an applet from secretly running a key logger in the background). Apparently the operation you're trying to do isn't allowed either.
To solve this, you have to sign your applet. A signed applet is allowed to run under normal security permissions. To do that you have to create a security certificate and sign your applet with jarsigner.
No need to buy expensive certificates, at least not if this is a small personal project. A self-signed certificate will do (the only trouble is that the browser will pop-up a message saying "certificate could not be confirmed" or something like that).
See also: Signed applet tutorial
@ Dave
In addition to getting your jar signed you have to ensure the code you need marked as privileged is wrapped in a privileged block.
final String googleUrl = "www.google.com"
URL url = (URL) AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
return new URL(googleUrl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
}
});
精彩评论