I am trying understand the basics of java security and AccessController.doPrivileged() usage i started with a sample program
import java.security.AccessController; import java.security.PrivilegedAction; public class AccessSystemProperty { public static void main(String[] args) { System.out.println(System.getSecurityManager()); AccessController.doPrivileged( new PrivilegedAction<Boolean>(){ public Boolean run(){ System.out.println(System.getProperty("java.home")); return Boolean.TRUE; } } ); } }
if i try to run above code using default security manage i am getting AccessControlException My stacktrace is
C:\>java -Djava.security.manager AccessSystemProperty java.lang.SecurityManager@923e30 Exception in thread "main" java.security.AccessControlException: access denied ( java.util.PropertyPermission java.home read) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPropertyAccess(Unknown Source) at java.lang.System.getProperty(Unknown Source) at AccessSystemProperty$1.run(AccessSystemProperty.java:9) at AccessSystemProperty$1.run(AccessSystemProperty.java:8) at java.security.AccessController.doPrivileged(Native Method) at AccessSystemProperty.main(AccessSystemProperty.java:6)
Kindly help me to get a clear picture of
1)when we need to use AccessController.doPrivileged() ?.(if SecurityManager is present we use AccessController.doPrivileged why this is failing in above example ) 2) what is the real advantage we are getting by using AccessController and PrivilegedAction?. 3) Do we need custom policy file for above example to work ? Thanks, Paul