java 安全策略没有按预期工作,总是给出 AccessControlException

标签 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)

我哪里错了,如何改正?

非常感谢。

最佳答案

myPolicy.txtcodeBase URL 中使用正斜杠而不是反斜杠。您可能还需要在“类”和“*”之间使用斜杠。

根据 PolicyFiles documentation :

Note: a codeBase value is a URL and thus should always utilize slashes (never backslashes) as the directory separator, even when the code source is actually on a Windows system. Thus, if the source location for code on a Windows system is actually C:\somepath\api\, then the policy codeBase entry should look like:

grant codeBase "file:/C:/somepath/api/" {
    ...
};

关于java 安全策略没有按预期工作,总是给出 AccessControlException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53728802/

相关文章:

java - 安卓java.security.cert.CertPathValidatorException : Trust anchor for certification path not found

c# - NullReferenceException 与 ArgumentNullException

java - 需要帮助从主图表打开子图表?

java.lang.ClassCastException : android. 小部件.TextView。为什么我会得到这个?

java - StompFrameHandler 没有从消息中获取有效负载

javascript - ruby rails : how to pass JSON to JavaScript

maven - Mule 安全属性占位符 Maven 设置

c++ - C++ 异常处理增加了多少占用空间

c# - 返回对象时如何抛出异常?

java - For 循环不终止