Today's Question:  What weekend projects have you created?        GIVE A SHOUT

Technical Article => Programming =>  Java

Turn on SecurityManager in Java

  Pi Ke      2013-12-16 05:03:53      3,106    0

SecurityManager in Java is to check whether the application codes can access some restricted resource such as file, socket etc. This can be used in applications which have high security requirements. With this feature turned on, our system resources can be secured with only permitted operations.

When JVM starts, it will first check whether the SecurityManager is on by checking the system property, if it's on, then an instance of SecurityManager will be created and it can be used to check different permissions. By default the security manager is off, but there are a few ways we can turn on SecurityManager.

1. Specify

When we run a program, we can specify the JVM command to enable the SecurityManager.

java <class_name>

This is the most common way to turn on the SecurityManager. is a system property, you can using System.getProperty("") to check whether the system property is set. Here you may think, we can use System.setProperty("") to turn on SecurityManager, while this is not the case for SecurityManager as we mentioned previously this system property is checked when the JVM starts. If we set the property manually within the program, it will have no effect as the JVM has already started and passed the step checking the system property.

2. Turn on SecurityManager programmably

Now if we really want to turn on the SecurityManager in we programs, we can also achieve this. There is a method in the System class called setSecurityManager() which can do this. The parameter to this method is a SecurityManager instance.

SecurityManager sm=new SecurityManager();

With this, we can turn on the SecurityManager. If later we want to turn off the SecurityManager, what should we do? Will below codes work?

SecurityManager sm=System.getSecurityManager();

The above codes will work only if you also specified a permission in the java.policy file located at ${JAVA_HOME}/lib/security or the location you specified. The permission is:

permission java.lang.RuntimePermission "setSecurityManager";

The above line will allow code to set security manager in use.

3. In a build file

If we want to turn on SecurityManager while we are using Ant to build an application, we can put

<sysproperty key="" value="" />

This is useful when we create unit test cases with Ant



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


How programmer solves a problem

By sonic0002