Java Reference
In-Depth Information
Click here to view code image
private FileInputStream openFile() {
final FileInputStream f[] = { null };
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("file");
} catch(FileNotFoundException fnf) {
// Forward to handler
}
return null;
}
});
return f[0];
}
// Wrapper method
public void performActionOnFile() {
try (FileInputStream f = openFile()){
// Perform operation
} catch (Throwable t) {
// Handle exception
}
}
In this example, the trusted code grants privileges beyond those required to read a
file, even though read access to the file was the only permission needed by the doPriv-
ileged() block. Consequently, this code violates the principle of least privilege by
providing the code block with superfluous privileges.
Compliant Solution
The two-argument form of doPrivileged() accepts an AccessControlContext object
from the caller and restricts the privileges of the contained code to the intersection of
the privileges of the protection domain and those of the context passed as the second ar-
gument. Consequently, a caller that wishes to grant only permission to read the file can
provide a context that has only file-reading permissions.
An AccessControlContext that grants the appropriate file-reading permissions can
be created as an inner class:
Search WWH ::




Custom Search