security
Control access to an Object example
With this example we are going to demonstrate how to control access to an Object in Java. In short, to control access to an Object you should:
- Create a Guard, which is an object that is used to protect access to another object, with the String name of the system property, and a String of comma-separated actions granted on the property.
- Create a GuardedObject to encapsulate the target object and the Guard object. In this example the target object is a String password.
- In order to get the guarded object, we can invoke the
getObject()
API method of the GuardedObject. If the access to the object is not allowed, an AccessControlException is thrown.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.security.AccessControlException; import java.security.Guard; import java.security.GuardedObject; import java.util.PropertyPermission; public class ControlAccessToObject { public static void main(String[] args) { // The object that requires protection String password = new String("my_password"); /* The permission that will protect the object. In this case everyone (thread) who has read access to the "java.home" environment variable can access the object as well */ Guard guard = new PropertyPermission("java.home", "read"); // Create the guard GuardedObject guardedObject = new GuardedObject(password, guard); // Get the guarded object, only threads with the required permission can access the object. try { password = (String) guardedObject.getObject(); System.out.println("Protected object is " + password); } catch (AccessControlException e) { System.out.println("Cannot access the object - permission is denied"); } } }
Output:
Protected object is my_password
This was an example of how to control access to an Object in Java.