Java : Is there an API to find which class needs the permission in a Custom security manager class?

标签 java securitymanager

我试图在自定义安全管理器中查找哪个类动态请求了权限。我找不到任何 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/

相关文章:

java - 由: java. lang.NoClassDefFoundError引起:org/springframework/data/repository/support/PageableExecutionUtils

Java JDBC/SQLite : Export tables to sql statements

java - 什么是 Java 中的时间对象?

java - 安全管理器 java 停止覆盖

java - ModelMapper 中的 ClassCastException : EnhancerByModelMapper cannot be cast

java - Solr/tomcat 中的 SocketException 管道损坏

java.net.SocketPermission : "connect.resolve"

java - 无法从 jar 加载类定义

java - JFrame 中的沙盒 JPanel

java - 如何搭建沙箱环境