How to create conditions based on user role using JSF/MyFaces?

Chei picture Chei · Nov 13, 2008 · Viewed 8.7k times · Source

What options do I have to read the roles of the current user from my JSP pages? I'm aware of the visibleOnUserRole="myRole" attribute on Tomahawk components, but I need roles for a bit more complicated things than simple visibility.

Answer

McDowell picture McDowell · Nov 13, 2008

The ExternalContext exposes user and role information.

public class RolesAccess implements Serializable {

    public String getUserPrincipalName() {
        FacesContext context = FacesContext.getCurrentInstance();
        Principal principal = context.getExternalContext().getUserPrincipal();
        if(principal == null) {
            return null;
        }
        return principal.getName();
    }

    public String getUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getExternalContext().getRemoteUser();
    }

    public boolean isManager() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getExternalContext().isUserInRole("manager");
    }

}

If you're using JSF in servlets, this information maps to the values exposed by the HttpServletRequest.

You can use managed beans to expose values to the view via the Expression Language.

<f:view>
    <h:outputLabel value="#{rolesBean.userPrincipalName}" />
    <h:outputLabel value="#{rolesBean.user}" />
    <h:outputLabel value="#{rolesBean.manager}" />
</f:view>