Java安全策略无法按预期运行,请始终提供AccessControlException

时间:2018-12-11 16:53:12

标签: java security exception permissions policy

首先,我有以下工作代码:

import java.io.FileWriter;
import java.io.IOException;
public class TestPolicy {
    public static void main(String[] args) {
        FileWriter writer;
        try {
            writer = new FileWriter("testPolicy.txt");
            writer.write("hello1");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

一起运行良好
D:\Documents\myproject\mynet\mytest\java\security\target\classes>java -classpath . TestPolic

它将生成一个名为[testPolicy.txt]的新文件

然后我添加了一个../../src/myPolicy.txt,内容为:

grant codeBase "file:D:\Documents\myproject\mynet\mytest\java\security\target\classes*" {
    permission java.io.FilePermission "testPolicy.txt", "read,write";
};

我希望,只要我指定了“读,写”权限,它也应该运行良好。但是它运行异常:

D:\Documents\myproject\mynet\mytest\java\security\target\classes>java -classpath . -Djava.security.manager -Djava.security.policy=../../src/myPolicy.txt TestPolicy
Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "testPolicy.txt" "write")
        at java.security.AccessControlContext.checkPermission(Unknown Source)
        at java.security.AccessController.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkWrite(Unknown Source)
        at java.io.FileOutputStream.<init>(Unknown Source)
        at java.io.FileOutputStream.<init>(Unknown Source)
        at java.io.FileWriter.<init>(Unknown Source)
        at TestPolicy.main(TestPolicy.java:8)

我在哪里弄错了,如何解决?

非常感谢。

1 个答案:

答案 0 :(得分:1)

codeBase的{​​{1}} URL中使用正斜杠而不是反斜杠。您可能还需要在“类”和“ *”之间加一个斜杠。

根据PolicyFiles documentation

  

注意:codeBase值是一个URL,因此即使代码源实际上在Windows系统上,也应始终使用斜杠(绝不使用反斜杠)作为目录分隔符。因此,如果Windows系统上代码的源位置实际上是C:\ somepath \ api \,则策略codeBase条目应类似于:

myPolicy.txt