使用Security Manager保护对象

时间:2012-12-11 16:13:29

标签: java security object

我想使用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>

1 个答案:

答案 0 :(得分:1)

您的代码在策略文件中缺少权限类定义。您的策略文件应如下所示:

grant codeBase "file:/C:/users/root/desktop/temp/temp2/program1.jar" {               
    permission CustomPermission "perm";
};

我认为CustomPermission应该由公共类在其自己的文件中。