4

I have code that relies on the NTSystem class (com.sun.security.auth.module.NTSystem) which is found in rt.jar for Windows JREs. But when I am compile my class on a Linux machine, it fails, because that class is not supplied with the Linux JDK/JRE.

Now, when RUNNING the code, it makes sense that I would be unable to use the NTSystem class and it's functions. But my code is smart enough to determine what OS it's running on, and to use the appropriate classes.

Conversely, developing in Windows, I don't have access to com.sun.security.auth.module.UnixSystem. Am I forced to use reflection to load and use these classes because of a compile time limitation? Or is there a special rt.jar that has all the classes in it for building purposes?

Thanks in advance.

w25r
  • 882
  • 10
  • 15
  • Use Java reflection - see the answer of celsowm here: http://stackoverflow.com/questions/797549/get-login-username-in-java – Alexander Feb 02 '15 at 17:00

2 Answers2

3

Create JAAS config files for each target platform or create entries for each platform in a single JAAS config. Then access the information through Java SE APIs without using the com.sun.* packages directly. This can be performed via the Java Authentication and Authorization Service (JAAS) (javax.security.auth.* and javax.security.auth.login.*). Create a JAAS config file with the following entry:

sampleApp {
    com.sun.security.auth.module.NTLoginModule required debug=false;
};

Save that entry as sampleapp_jaas.config. Next set the system property so Java will look for the config file.

-Djava.security.auth.login.config==sampleapp_jaas.config

Note that the double equals has special meaning. See the com.sun.security.auth.login.ConfigFile for details on the load order.

Then create LoginContext that will look for the entry in the JAAS config. Call login to populate the subject. From there, you can access information using the subject API. For instance the following example just list the groups assigned to the current user.

LoginContext l = new LoginContext("sampleApp");
l.login();
try {
    Subject s = l.getSubject();
    for (Principal p : s.getPrincipals()) {
        System.out.println(p);
    }
} finally {
    l.logout();
}

Using this setup, Java will use the com.sun.security.auth.module.NTSystem class to get the information but none of your code will be hardwired to the non-standard APIs.

jmehrens
  • 10,580
  • 1
  • 38
  • 47
0

If you really need these OS specific classes, I would get the source for them, compile them and create your own small library to compile against. 9Or you can use a copy of the classes from different installations)

I believe the OpenJDK has up to three flavours (including Solaris) so it wouldn't be too hard to create a simple library of them all.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130