开发者

SecurityManager StackOverflowError

开发者 https://www.devze.com 2022-12-24 09:25 出处:网络
Running the following code, I get a StackOverflowError at the getPackage() line. How can I grant permission just to classes inside package I wan开发者_StackOverflowt, if I can\'t access the getPackage

Running the following code, I get a StackOverflowError at the getPackage() line. How can I grant permission just to classes inside package I wan开发者_StackOverflowt, if I can't access the getPackage() to check the package?

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

}


Solved! Just add to the begin of the first checkPermission method:

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


If you just want to restrict packages, how about implementing checkPackageAccess and/or checkPackageDefinition instead the generic checkPermission?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号