Java security policy 简单的操作

package com.xiuye.security;

import java.io.FilePermission;
import java.security.AccessController;
import java.security.PrivilegedAction;

public class TestAccessController2 {

	public static void main(String[] args) {

		System.setSecurityManager(new SecurityManager());

		log(System.getProperty("java.security.policy"));

		PrivilegedAction pa = ()->{
			FilePermission fp = new FilePermission("com","read");
			AccessController.checkPermission(fp);
			return true;
		};
		log(AccessController.doPrivileged(pa));

	}
	private static void log(T t){
		System.out.println(t);
	}

}


<=>

package com.xiuye.security;

import java.io.FilePermission;
import java.security.AccessController;
import java.security.PrivilegedAction;

import sun.security.util.SecurityConstants;

public class TestAccessController2 {

	public static void main(String[] args) {

		//注意先后代码顺序
		System.setProperty("java.security.policy", "security.policy");
		System.setSecurityManager(new SecurityManager());

		log(System.getProperty("java.security.policy"));

		PrivilegedAction pa = ()->{
			FilePermission fp = new FilePermission("com",SecurityConstants.FILE_READ_ACTION);
			AccessController.checkPermission(fp);
			return true;
		};
		log(AccessController.doPrivileged(pa));

	}
	private static void log(T t){
		System.out.println(t);
	}

}


grant {
	permission java.io.FilePermission "com", "read";
	permission java.util.PropertyPermission "java.security.policy", "read";
};// 这里也需要";"!





security.policy
true






你可能感兴趣的:(Java,Error,Solution)