我想使用 java.security.manager 创建自定义权限。基本上我想创建一个权限,策略文件必须指定,以便执行我的 Java 应用程序的用户能够使用 Java 的 GuardedObject 功能访问我正在保护的对象。我似乎无法让它工作。请在下面找到具体信息。如果我做错了,请告诉我。我是 Java 安全管理器的新手:
应用程序源代码:
import java.security.AccessControlException;
import java.security.Guard;
import java.security.GuardedObject;
import java.util.PropertyPermission;
import java.security.*;
class person {}
class custompermission extends BasicPermission {
custompermission(String name) {
super(name);
}
custompermission(String name, String action) {
super(name,action);
}
}
public class program1 {
public static void main(String[] argv) throws Exception {
String person = "person";
Guard guard = new custompermission("perm");
GuardedObject gobj = new GuardedObject(person, guard);
try {
Object o = gobj.getObject();
} catch (AccessControlException e) {
e.printStackTrace();
}
}
}
我的 jar 的 Manifest.txt 文件:
Main-Class: program1
我的策略文件 - my.security.policy:
grant codeBase "file:/C:/users/root/desktop/temp/temp2/program1.jar" {
permission "perm";
};
程序的编译和jar文件的创建:
C:\Users\root\Desktop\temp\temp2>javac program1.java
C:\Users\root\Desktop\temp\temp2>jar -cvfm program1.jar Manifest.txt *.class
added manifest
adding: custompermission.class(in = 335) (out= 234)(deflated 30%)
adding: person.class(in = 188) (out= 162)(deflated 13%)
adding: personpermission.class(in = 335) (out= 232)(deflated 30%)
adding: program1.class(in = 790) (out= 488)(deflated 38%)
程序的执行:
C:\Users\root\Desktop\temp\temp2>java -Djava.security.manager -Djava.security.policy=my.security.policy -jar program1.jar
java.security.AccessControlException: access denied ("custompermission" "perm")
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.security.Permission.checkGuard(Unknown Source)
at java.security.GuardedObject.getObject(Unknown Source)
at program1.main(program1.java:37)
C:\Users\root\Desktop\temp\temp2>