SecurityManager StackOverflowError

时间:2010-03-24 19:10:03

标签: java security stack-overflow

运行以下代码,我在getPackage()行得到一个StackOverflowError。 如果我无法访问getPackage()来检查包,我如何只向我想要的包中的类授予权限?

package myPkg.security;

import java.security.Permission;

import javax.swing.JOptionPane;

public class SimpleSecurityManager extends SecurityManager {

    @Override
    public void checkPermission(Permission perm) {
 Class<?>[] contextArray = getClassContext();
 for (Class<?> c : contextArray) {
     checkPermission(perm, c);
 }
    }

    @Override
    public void checkPermission(Permission perm, Object context) {
 if (context instanceof Class) {
     Class clazz = (Class) context;
     Package pkg = clazz.getPackage(); // StackOverflowError
     String name = pkg.getName();
     if (name.startsWith("java.")) {
  // permission granted
  return;
     }
     if (name.startsWith("sun.")) {
  // permission granted
  return;
     }
     if (name.startsWith("myPkg.")) {
  // permission granted
  return;
     }
 }
 // permission denied
 throw new SecurityException("Permission denied for " + context);
    }

    public static void main(String[] args) {
 System.setSecurityManager(new SimpleSecurityManager());
 JOptionPane.showMessageDialog(null, "test");
    }

}

2 个答案:

答案 0 :(得分:1)

解决!只需添加到第一个checkPermission方法的开头:

if (perm instanceof FilePermission) {
    if (perm.getActions().equals("read")) {
    // grant permission
    return;
    }
}

答案 1 :(得分:0)

如果您只想限制软件包,那么如何实现checkPackageAccess和/或checkPackageDefinition而不是通用checkPermission呢?