I have the following JSF 2.1 login form, running in Glassfish 3.1
I came up with the following solution to add roles programmatically after login, which works at least on GlassFish 3.1.2 build 23.
import com.sun.enterprise.security.SecurityContext;
import com.sun.enterprise.security.web.integration.PrincipalGroupFactory;
import java.security.Principal;
import java.util.Set;
import javax.security.auth.Subject;
import org.glassfish.security.common.Group;
public class GlassFishUtils {
public static void addGroupToCurrentUser(String groupName, String realmName) {
Subject subject = SecurityContext.getCurrent().getSubject();
Set principals = subject.getPrincipals();
Group group = PrincipalGroupFactory.getGroupInstance(groupName, realmName);
if (!principals.contains(group))
principals.add(group);
}
}
You will need to add security.jar
and common-util.jar
from GlassFish to your project libraries.
And don't forget to create a
section in your web.xml for the roles you wish to add.
Note that I am using functionality which does not appear to be part of a published stable API, so there is no guarantee that this will keep working in future releases of GlassFish.
I got the information on how to add roles from the source code of sun.appserv.security.AppservPasswordLoginModule.commit()
of GlassFish.
If a future GlassFish release breaks my code, this function would be a good place to start in order to find out how to fix it.