Hi,
This is how i do it (not sure it is a best way but it works for me ;) ):
import com.sun.enterprise.security.auth.login.PasswordCredential;
/**
* Returns current subject's user name. Subject is taken from current calling context.
* User name is extracted from first found private <code>PasswordCredential</code>.
* Returns <code>null</code> if subject can not be retrieved or it does not contain private
* <code>PasswordCredential</code> or user name in <code>PasswordCredential</code> is not set.
*
* @return <code>String</code> current user's name or null.
*/
public static String getCurrentUserName () {
if (log.isLoggable (Level.FINER)) {
log.entering (CLASS_NAME, "getCurrentUserName");
}
String userName = null;
Subject subject = Subject.getSubject (AccessController.getContext ());
if (subject != null) {
if (log.isLoggable (Level.FINEST)) {
log.finest ("Got subject: " + subject.toString ());
}
Set<Object> privateCredentials = subject.getPrivateCredentials (Object.class);
for (Object credential : privateCredentials) {
if (credential instanceof PasswordCredential) {
if (log.isLoggable (Level.FINEST)) {
log.finest ("Got instance of PasswordCredential: " + credential.toString ());
}
userName = ((PasswordCredential) credential).getUser ();
break;
}
}
}
else {
if (log.isLoggable (Level.FINEST)) {
log.finest ("Subject not found in current context.");
}
}
if ("".equals (userName)) userName = null;
if (log.isLoggable (Level.FINER)) {
log.exiting (CLASS_NAME, "getCurrentUserName", userName);
}
return userName;
}
-
Aleksandras Novikovas
On Mon, 2009-01-26 at 06:42 -0800, glassfish_at_javadesktop.org wrote:
> I have a long history with BEA WebLogic but am I relative newcomer to Glassfish. One Weblogic capability I used extensively was to retrieve the username from the system and use it to provide access control as well as data marking (createor/updater/etc). This prevented me from having to pass around "username" to all my EJB methods.
>
> import weblogic.security.Security;
> import weblogic.security.SubjectUtils;
> import javax.security.auth.Subject;
>
> public String whoAmI() {
> Subject s = new Security().getCurrentSubject();
> return SubjectUtils.getUsername(s);
> }
>
> As ypu can see, the example utilizes 2 weblogic specific packages.
>
> Does Glassfish provide this capability?
>
> Thanks,
>
> Joe
> [Message sent by forum member 'janchj' (janchj)]
>
> http://forums.java.net/jive/thread.jspa?messageID=328170
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_glassfish.dev.java.net
> For additional commands, e-mail: users-help_at_glassfish.dev.java.net
>