|
Java™ by example!
|
|
|
What is privileged code?
It allows you to temporarily grant permission to code that would normally not have permission to run. Normally, the entire execution stack (all callers) needs to have permission to do a sensitive operation.
With Privileged Code, you can specify in a fine-grained way that only the final class in the execution stack needs permission. For example, consider the following two classes. Main.java:
LowLevel.java:
The Main class just executes the static method executeLowLevelAction that gets the property test. Run log:
As you expected, the first run can just get the property test without needing any permissions (as no security manager is installed by default). In the second run, we ask the VM to set up a default SecurityManager which results in an AccessControlException because reading System Property "test" is not allowed. To grant permission to read this property, we need to write a policy security configuration file. But we really only want the class LowLevel to have permission to read the property. We do not want to grant the calling class Main that permission. So what we could do is jar the LowLevel class up and write a policy file to grant that jar file additional permissions:
mypolicy:
Run log:
AccessControlException!!? How come? Didn't we grant the permission to LowLevel.jar to read the property "test"? The problem lays in the requirement that every class in the execution stack must have the permission. The solution is to make the System.getProperty call in a Privileged Block. This could be done as follows. LowLevel.java:
Compile and jar it up:
and run it again:
Now we get the correct response: allowing only the class LowLevel to run "sensitive" code, no matter who called it, so without worrying about the executing stack.
Further Information
Author of answer: Joris Van den Bogaert
Comments
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|