Strange behaviour of AccessController.checkPermission

偶尔善良 提交于 2019-12-13 19:18:13

问题


I am trying to learn about Java's permission model. I tried this sample code:

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 throws an exception in the end:

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

Why is it that the file read works fine, but a check for the permission gives a negative result?


回答1:


Likely because the JVM doesn't have a SecurityManager configured. Without a SecurityManager configured there will be no AccessController call made.

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




回答2:


There's nothing strange here, this is exactly the behavior specified in the javadoc. The checkPermission method will throw if the permission is not granted:

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

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

Throws: IllegalArgumentException - If actions is null, empty or contains an action other than the specified possible actions.



来源:https://stackoverflow.com/questions/23476145/strange-behaviour-of-accesscontroller-checkpermission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!