本文介绍了AccessController.checkPermission的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解Java的权限模型.我尝试了以下示例代码:

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
}

这可以很好地打印/etc/passwd的内容,但最终会引发异常:

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")

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?

推荐答案

可能是因为JVM没有配置SecurityManager.如果未配置SecurityManager,将不会进行AccessController调用.

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

这篇关于AccessController.checkPermission的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 23:17