JEP 486:Permanently Disable the Security Manager
JEP486:该特性为一个正式特性,不论客户端还是服务端,SecurityManager已经不再是安全方面的首选,在Java17的JEP411被标注为Deprecated,在Java24将其禁用。
SecurityManager是Java的一种安全机制,用于控制应用程序的权限,限制对系统资源(文件、网络、运行时、属性、反射等)的访问。
试用一下SecurityManager,先写一段代码打印SecurityManager,并读取文件,打印其内容,最后打印一下os.name属性。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SecurityManagerTest {
    public static void main(String[] args)throws FileNotFoundException {
        System.out.println("SecurityManager: " + System.getSecurityManager());
        try (FileInputStream fis = new FileInputStream("/yourpath/to/file")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("OS name: " + System.getProperty("os.name"));
    }
} 
在Java17环境运行:

 
此时没有添加SecurityManager直接运行,SecurityManager打印为null。
添加启动参数-Djava.security.manager运行:

因为在Java17特性中被标注为Deprecated,因此打印了WARNING,并打印了SecurityManager,但读文件没有做授权,抛出了AccessControlException异常。
添加policy文件授权文件的读取权限

添加参数-Djava.security.policy运行:

这里发现os.name也读取出来了,这是因为Java的安全策略默认包含了一些基础权限,如果换成file.encoding,则需要添加额外的读取授权

换成Java24

再次执行:

SecurityManager已经掉队了。
                  
                  
                  
                  
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					60
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            