我试图在自定义安全管理器中查找哪个类动态请求了权限。我找不到任何 API 可以帮助我获取调用类的代码库位置。以下是我正在尝试做的事情,
我有一个 testApp 类尝试写入文件,
package test.ProfilingSecurityManager;
import java.io.PrintWriter;
public class TestApp {
public static void main(String [] args) throws Exception {
System.setSecurityManager(new NewProfilingSecurityManger());
PrintWriter writer = new PrintWriter("profile.txt");
writer.println("Test line");
writer.close();
}
}
自定义安全管理器中重写的方法如下,
public void checkPermission(final Permission permission) {
try {
// see what the parent security manager code says
super.checkPermission(permission);
}
catch (Exception e) {
// find the code base which requested this permission
// I can get the call stack here
Class [] sourceClasses = getClassContext();
Class invokingClass = sourceClasses[sourceClasses.length - 1];
// I can also get the accesscontrol context here
// using -AccessController.getContext()
// How do i find the codebase location of the class
// which needed this permission here
}
}
当在 checkPermission 方法中抛出异常时,我需要找到 TestApp 的代码库位置。 有人可以帮我解决这个问题吗?
谢谢
最佳答案
如果您调用 invokingClass.getProtectionDomain().getCodeSource(),这将告诉您该类是从哪里加载的。
但是,这只会告诉您当访问检查失败时哪个类位于调用堆栈的底部。在您给出的示例中,这将是 TestApp,但如果您尝试调试安全权限问题,更好的方法是运行 Java,并将 java.security.debug
系统属性设置为 访问,失败
。当权限检查失败时,这会告诉您哪个类没有权限,它是从哪里加载的,以及它拥有什么权限。
关于Java : Is there an API to find which class needs the permission in a Custom security manager class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437623/