Sunday 9 October 2011

Sample Code for Impersonation Service in Websphere Portal Server

Impersonation allows a user, such as a support specialist, to access a user’s workstation to test out a new page, portlet, and so on, and see issues as they occur on the workstation. 

Impersonation was a new security feature introduced in Websphere Portal Server 6.1.5. It can be enabled through few configurations mentioned below and can be used programmatically as I will be explaining later. But there is no out-of-box portlet for impersonation implementation in Websphere Portal Server 6.1.5.

Steps to follow for impersonation in Websphere Portal Server
Step 1:
WAS configurations to enable user impersonation:
1. Log on to the WebSphere Application Server Integrated Solutions Console or Network Deployment Administration Console.
2. Perform the following steps to enable the Impersonation feature:
    a. Navigate to Resources > Resource Environment > Resource Environment Providers > WP Authentication Service > Custom Properties.
    b. Click New.
    c. Enter logout.explicit.filterchain in the Name field.
    d. Enter com.ibm.wps.auth.impersonation.impl.ImpersonationLogoutFilter in the Value field.
    e. Click Apply and then click Save to save the changes directly to the master configuration.
    f. Navigate to Resources > Resource Environment > Resource Environment Providers > WP PortletServiceRegistryService > Custom Properties.
    g. Click New.
    h. Enter jndi.com.ibm.portal.portlet.service.impersonation.ImpersonationService in the Name field.
    i. Enter com.ibm.wps.portletservice.impersonation.impl.ImpersonationServiceImpl in the Value field.
    j. Click Apply and then click Save to save the changes directly to the master configuration.

3. Stop and restart the WebSphere_Portal server.
Step 2: 
Portal configuration to assign delegator role to proper group or user who can impersonate other users :
    a. Log on to WebSphere Portal as the Administrator.
    b. Click Administration.
    c. Click Access > User and Group Permissions.
    d. Click Users or User Groups.
    e. Search for the user or group you want to assign as Delegator.
    f. Click the Select Resource Type icon for the required user.
    g. Navigate to the page that contains the Virtual Resources option, using the Page Next button and click that link.
    h. Navigate to the page that contains the USERS option and click the Assign Access icon.
    i. Select the Explicitly Assign checkbox for the Delegator role.
    j. Click OK.
    k. Verify that the required user now has User and Delegator access.
The user(s) or groups with the Delegator role can now impersonate another user.

Initial  Screen:

I logged as wasadmin and able to see all portlets available in page.


I impersonate to "user1" user .

After impersonate





Only user1 visible portlets are seen in the page.

Sample Code:

package com.ibm.myuserimpersonationservice;
import java.io.*;
import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.portlet.*;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.impersonation.ImpersonationService;
import com.ibm.portal.um.PumaLocator;
import com.ibm.portal.um.User;
import com.ibm.portal.um.exceptions.PumaAttributeException;
import com.ibm.portal.um.exceptions.PumaMissingAccessRightsException;
import com.ibm.portal.um.exceptions.PumaModelException;
import com.ibm.portal.um.exceptions.PumaSystemException;
import com.ibm.portal.um.portletservice.PumaHome;
/**
 * The user impersonation feature in WebSphere Portal allows specified users or groups the ability to assume the profile of others.
 *
 */
public class MyUserimpersonationServicePortlet extends GenericPortlet {

    public static final String JSP_FOLDER    = "/_MyUserimpersonationService/jsp/";    // JSP folder name

    public static final String VIEW_JSP      = "MyUserimpersonationServicePortletView";         // JSP file name to be rendered on the view mode
    PortletServiceHome pshimpersonate;
    PumaHome pumaHome;
    /**
     * @see javax.portlet.Portlet#init()
     */
    public void init() throws PortletException{
        super.init();
        try {                                               
            Context ctx = new InitialContext();                                               
            pshimpersonate = (PortletServiceHome)ctx.lookup(ImpersonationService.JNDI_NAME);
            PortletServiceHome pshome;                                               
            pshome = (PortletServiceHome) ctx.lookup(PumaHome.JNDI_NAME);                                               
            pumaHome = (PumaHome)pshome.getPortletService(PumaHome.class);                                
            }
        catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

    /**
     * Serve up the <code>view</code> mode.
     *
     * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
     */
    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        // Set the MIME type for the render response
        response.setContentType(request.getResponseContentType());
        // Invoke the JSP to render
        PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
        try {
            List list=pumaHome.getLocator(request).findUsersByDefaultAttribute("*");
            ArrayList attribs = new ArrayList();
            attribs.add("cn"); // Chose the type of attribute you want
            Iterator it=list.iterator();
            ArrayList names=new ArrayList();
            while(it.hasNext())
            {
                User user=(User)it.next();
                Map group_attribs = pumaHome.getProfile(request).getAttributes(user, attribs);
                String user_cn = (String) group_attribs.get((Object) "cn");
                names.add(user_cn);
            }
            if(names.size()>0) request.setAttribute("names", names);
               
        } catch (PumaSystemException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (PumaAttributeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (PumaMissingAccessRightsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (PumaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        rd.include(request,response);
    }

    @ProcessAction(name="switchUser")
    public void impersonateAction(ActionRequest request,ActionResponse response)throws PortletException, java.io.IOException, PumaSystemException,PumaAttributeException, PumaMissingAccessRightsException, MyException
    {
        System.out.println("Entering UserImpersonationPortlet.impersonateAction()");
        //Getting Form data
        String user_cn = request.getParameter("user_cn");
        System.out.println("User-cn : " + user_cn);
        // obtain the service object and use the service
        ImpersonationService impersonationService = (ImpersonationService) pshimpersonate.getPortletService(ImpersonationService.class);
        PumaLocator pumaLocator = pumaHome.getLocator(request);
        List<User> users = pumaLocator.findUsersByAttribute("cn", user_cn);;
        if (users.size() > 0) {
        try {
            impersonationService.doImpersonate(request, response, users.get(0));
           
        }
        catch (Throwable e)
        {    
            throw new MyException();
        }
       
        }
}

    /**
     * Returns JSP file path.
     *
     * @param request Render request
     * @param jspFile JSP file name
     * @return JSP file path
     */
    private static String getJspFilePath(RenderRequest request, String jspFile) {
        String markup = request.getProperty("wps.markup");
        if( markup == null )
            markup = getMarkup(request.getResponseContentType());
        return JSP_FOLDER + markup + "/" + jspFile + "." + getJspExtension(markup);
    }

    /**
     * Convert MIME type to markup name.
     *
     * @param contentType MIME type
     * @return Markup name
     */
    private static String getMarkup(String contentType) {
        if( "text/vnd.wap.wml".equals(contentType) )
            return "wml";
        else
            return "html";
    }

    /**
     * Returns the file extension for the JSP file
     *
     * @param markupName Markup name
     * @return JSP extension
     */
    private static String getJspExtension(String markupName) {
        return "jsp";
    }

}

<%@page session="false" contentType="text/html" pageEncoding="ISO-8859-1" import="java.util.*,javax.portlet.*,com.ibm.myuserimpersonationservice.*" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>   
<%@taglib prefix="c_rt" uri="http://java.sun.com/jstl/core_rt"%>   
<portlet:defineObjects/>
<% String userId = request.getRemoteUser();%>
<portlet:actionURL var="switchUserUrl">
 <portlet:param name="javax.portlet.action" value="switchUser" />
 </portlet:actionURL>
 <h4>Current User - <%=userId %>
 </h4><h4>Choose name of the user to impersonate</h4>
 <form method="post" action="<%=switchUserUrl %>">
 <table> 
<c_rt:forEach var="userCN" items="${requestScope.names}">
 <tr>  
  <td>
  <input type="radio" name="user_cn"  value="${userCN}"/>
  ${userCN}
  </td>
   </tr>
   </c_rt:forEach>
    <tr>   
    <td><input type="submit" name="submit" />
    </td> 
    </tr>
   </table>
 </form>

Click here to download the source code




No comments:

Post a Comment