6 ago 2013

Obtaining user LDAP groups from Weblogic / WebCenter security provider

Sometimes you need to obtain the groups where a user is member. You can check if a user is in a group with a common and simple EL:

#{securityContext.userInRole['Administrators']}

This EL will return true if the user is a member of that group.


In other cases you need the full list of groups where users belongs to, you can achieve this purpose with 2 different solutions.

Weblogic mode


    /**
     * This method returns the default IdentityStore of Weblogic
     * @return
     * @throws JpsException
     */
    private static IdentityStore getIdentityStore() throws JpsException
    {
        JpsContextFactory ctxf = JpsContextFactory.getContextFactory();
        JpsContext ctx = ctxf.getContext();
        IdentityStoreService storeService = ctx.getServiceInstance(IdentityStoreService.class);
        return storeService.getIdmStore();
    }

    /**
     * This method returns a list of the groups where the user belongs to
     * @param userName
     * @return
     */
    public List getRolesFromLDAP()
    {
        List rolesGranted = new ArrayList();
        IdentityStore is = null;
        try
        {
            is = getIdentityStore();
            
            //Getting current user
            ADFContext ctxt = ADFContext.getCurrent();
            SecurityContext sctxt = ctxt.getSecurityContext();

            User userAux = is.searchUser(sctxt.getUserPrincipal());
            RoleManager rm = is.getRoleManager();
            SearchResponse response = rm.getGrantedRoles(userAux.getPrincipal(), false);
            
            while (response.hasNext())
            {
                String name = response.next().getName();
                LOG.info("Añadiendo el rol:" + name);
                rolesGranted.add(name);
            }
            
        }
        catch (Exception e)
        {
            LOG.severe("Error obteniendo los grupos del usuario", e);
        }
        
        return rolesGranted;
    }


WebCenter mode


    public List getRolesWebCenter() throws WCSecurityException
    {
        List roles = new ArrayList();
        ADFContext ctxt = ADFContext.getCurrent();
        SecurityContext sctxt = ctxt.getSecurityContext();
        
        Collection collection = WebCenterSecurityUtils.getEnterpriseRoles(sctxt.getUserName());
        
        for (Principal user : collection)
        {
            String userName = user.getName();
            LOG.info("Role:" + userName);
            roles.add(userName);
        }
        
        return roles;
    }

Here is for download a sample project with this two samples.

And this is a capture of the results