I want to set a custom Policy
by defining my own class that extends the Policy class as follows:
public class MyPolicy extends Policy {
public MyPolicy() {
super();
}
@Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
// return PermissionCollection with no permissions
PermissionCollection pc = new PermissionCollection();
return pm;
}
}
Then, at the beginning of my application I set the my custom Policy
class and I also enable the SecurityManager
so that the new policy is in effect:
Policy.setPolicy(new MyPolicy());
System.setSecurityManager(new SecurityManager());
The problem with the above is that it doesn't work. The idea of the above example is to introduce a Policy that will prevent the application from doing anything that would require any kind of permission. So, for example, when I my application executes:
System.getenv();
I expect the above to result in AccessControlException
that should be thrown by the SecurityManager
. Instead, my application runs just fine. However, when I initialize the Policy and the SecurityManager
as follows:
// setting the policy twice intentionally
Policy.setPolicy(new MyPolicy());
Policy.setPolicy(new MyPolicy());
System.setSecurityManager(new SecurityManager());
Then executing System.getenv()
actually results in the expected AccessControlException
.
Here are my questions/concerns that I'd like to get an explanation on:
- why do I have to set a Policy twice to make the Policy be in effect after setting the SecurityManager?
- is it above issue some kind of bug or was the Policy class intentionally design to behave this way (if so - why?)?