Java Reference
In-Depth Information
Returning to the example of a service for appending a message to a log file, you
trust the bundle containing the service implementation, but you don't want to give
direct file system access to anyone else. To do this, your service must encapsulate its
file system operations inside a PrivilegedAction and use doPrivileged() like this:
public void append(String msg) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
doFileAppend();
}
});
}
else {
doFileAppend();
}
}
Any triggered permission checks stop walking the call stack at the run() method,
which means nontrusted code further up the stack won't have its protection domain
checked for the triggered permissions. Pushing this example further, you may decide
to limit which code can call the append() method. To so this, you can create your own
Permission subclass, which you can grant to code. For the append method, if you cre-
ate an AppendPermission , it can check the permission before performing the privi-
leged call:
public void append(String msg) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AppendPermission());
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() { doFileAppend(); }});
} else {
doFileAppend();
}
}
Here your service asks the SecurityManager to check whether the code on the call
stack has been granted the custom AppendPermission . If so, it can continue to per-
form the file-append operation; otherwise, a security exception is thrown.
WARNING You may have noticed that you check whether the security man-
ager is null before performing security checks. You do it this way because you
want to perform security checks only if security is enabled, to avoid perfor-
mance penalties when it's not enabled.
That pretty much sums up the important pieces of the Java security architecture.
These mechanisms provide for flexible, fine-grained security management. A poten-
tial downside is that managing all these permissions can be complex. Luckily, the OSG i
specification lessens some of this complexity by defining services to help you perform
Search WWH ::




Custom Search