Strange behavior of AccessController.checkPermission

I am trying to learn about the Java resolution model. I tried this code example:

public static void main(String[] args) { File file = new File("/etc/passwd"); try (BufferedReader reader = new BufferedReader(new FileReader(file));) { reader.lines().forEach(s -> System.out.println(s)); } catch (IOException e) { e.printStackTrace(); } FilePermission perm = new FilePermission("/etc/passwd", "read"); AccessController.checkPermission(perm); // throws Exception } 

This prints the contents of /etc/passwd fine, but at the end throws an exception:

Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "" "read")

Why is reading the file working fine, but checking the resolution gives a negative result?

+1
source share
2 answers

Probably since the JVM does not have a SecurityManager configured. Without the configured SecurityManager, the AccessController will not be called.

http://docs.oracle.com/javase/8/docs/technotes/guides/security/spec/security-spec.doc6.html#a19349

+1
source

There is nothing strange here, this is exactly what is indicated in javadoc. The checkPermission method will throw if permission is not granted :

Throws: AccessControlException - if the specified permission is not allowed based on the current security policy.

while the constructor for FilePermission will not quit if the specified permission is not granted, but only if the input is invalid :

Throws: IllegalArgumentException - if the actions are empty, empty or contain an action other than the specified possible actions.

0
source

All Articles