I know it must be a very easy question, but I am new to java and find it hard to get exact code that I need. What I need to be able to do is to get currently logged in username
This can be done through the Java SE APIs without using the com.sun.* packages directly. Use Java Authentication and Authorization Service (JAAS) (javax.security.auth.* and javax.security.auth.login.*) to access this information. 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 then access principals which represent the user groups.
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.