Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AccessController.doPrivileged

I am trying to figure out what some legacy code is doing. What exactly is this line doing, and why would I need it this way?

String lineSeparator = (String) java.security.AccessController.doPrivileged(
       new sun.security.action.GetPropertyAction("line.separator")); 

I found it in the logger implementation of the web/ejb application running on Weblogic 8. There are no special security policies enabled as far as I know. (I do not like imports from sun.* packages, so I want to get rid of this line ;-)

like image 793
Peter Kofler Avatar asked May 12 '09 12:05

Peter Kofler


People also ask

What is AccessController?

AccessController class is part of Java's security mechanism; it is responsible for enforcing the applicable security policy. This class's static doPrivileged() method executes a code block with a relaxed security policy. The doPrivileged() method stops permissions from being checked further down the call chain.

How can Java code temporarily assume additional privileges?

checkPermission method first checks if the method System. getSecurityManager returns null. Marking code as privileged enables a piece of trusted code to temporarily enable access to more resources than are available directly to the code that called it. This is necessary in some situations.

What is AccessController in Java?

More specifically, the AccessController class is used for three purposes: to decide whether an access to a critical system resource is to be allowed or denied, based on the security policy currently in effect, to mark code as being "privileged", thus affecting subsequent access determinations, and.

Does privileged block?

doPrivileged method takes an object of type java. security. PrivilegedAction and invokes its run method in privileged mode. The implementation guarantees that privileges will be revoked after the run method is executed, even if execution of doPrivileged is interrupted by an asynchronous exception.


1 Answers

It is just getting a system property. Retrieving system properties requires permissions which the calling code may not have. The doPrivileged asserts the privileges of the calling class irrespective of how it was called. Clearly, doPrivileged is something you need to be careful with.

The code quoted is the equivalent of:

String lineSeparator = java.security.AccessController.doPrivileged(     new java.security.PrivilegedAction<String>() {         public String run() {             return System.getProperty("line.separator");         }     }  ); 

(Don't you just love the conciseness of Java's syntax?)

Without asserting privileges, this can be rewritten as:

String lineSeparator = System.getProperty("line.separator"); 
like image 117
Tom Hawtin - tackline Avatar answered Sep 24 '22 17:09

Tom Hawtin - tackline