Documentation‎ > ‎WebSphere Portal‎ > ‎

Using Shared Credential Vault Slot in WebSphere Portal 6.1

Description

Introduction
This article analyzes sample portlet  that  uses shared credential vault slot in WebSphere Portal 6.1. The credentials set in shared vault slot by a user can be accessed from any of the portlets of user. Portlet can get the vault slot by iterating through all accessible slots and finding the one that matches the resource name. The sample portlet  is developed using JSR 286 APIs. Here is the outline of the portlet project.
  • The sample portlet supports Personalize mode (aka Edit mode)  and shows HTML form with the username and password fields using edit mode JSP. Clicking on the submit button causes the processAction method of the portlet to be invoked.
  • The processAction method calls getSharedSlotId. This method iterates through accessible slots for this portlet, and returns null or slot ID that matches resource name defined in portlet.xml. If the slot is not already created, it will create vault slot using private method createSlot. After vault slot is created, it will store submitted credentials of user using vault service.
  • When portlet is displayed in view mode and the credentials are not already set, portlet will show message to the user to choose personalize mode. If the credentials are already set, it will call private method getCredential() to retrieve credentials from the vault slot and display them.

Analysis of  Portlet Project
This section dissects portlet java code and explains imported packages, portlet life cycle methods and implemented private methods that handle credential vault APIs to create  shared vault slot, set credentials and retrieve credentials. Moreover, it shows JSP used in edit mode of portlet.

1. Configuration parameter: The following portlet configuration parameter is defined for the resource name.

Listing 1
<init-param>
            <name>sharedSlotResourceName</name>
            <value>myBankAppResource2</value>
 </init-param>

2. Packages: The sample uses following packages. You need to use credential vault from the package com.ibm.portal.portlet.service instead of deprecated com.ibm.wps.portletservcie package.

Listing 2
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.portlet.*;
import com.ibm.portal.ObjectID;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.credentialvault.CredentialSlotConfig;
import com.ibm.portal.portlet.service.credentialvault.CredentialVaultException;
import com.ibm.portal.portlet.service.credentialvault.CredentialVaultService;
import com.ibm.portal.portlet.service.credentialvault.credentials.UserPasswordPassiveCredential;
 

3. Initializing Vault Service:  The following code shows how to initialize vault service from the init() method of portlet. The service is assigned into a static variable of the class. The configuration parameter for the resource defined in step1 is also assigned into the static variable.

Listing 3
private static CredentialVaultService vaultService = null;
    private static String sharedSlotResourceName = null;
   
    public void init() throws PortletException{
        super.init();
        sharedSlotResourceName = getInitParameter("sharedSlotResourceName");
        try
        {
            Context context = new InitialContext();
            PortletServiceHome vaultServiceHome = (PortletServiceHome)context
 .lookup("portletservice/com.ibm.portal.portlet.service.credentialvault.CredentialVaultService");
            if(vaultServiceHome != null)
                vaultService = (CredentialVaultService)vaultServiceHome.
getPortletService(com.ibm.portal.portlet.service.credentialvault.CredentialVaultService.class);
        }
        catch(Exception e)
        {
            throw new PortletException("Error while getting vault service", e);
        }
    }


4. Creating Slot: The following code creates credential vault slot by passing resource name defined from portlet.xml. The vault slot is created as shared by  passing bPrivate parameter as false and as passive credential by passing bActive parameter as false.

Listing 4
private String createSlot(ActionRequest request) throws Exception
    {
       
        String resourceName = sharedSlotResourceName; //For shared slot resource name should be slot name
        ObjectID segmentID = vaultService.getDefaultUserCredentialSegmentId();
        HashMap<String, String> descriptionsMap = new HashMap<String, String>();
        HashMap<String, String> keywordsMap = new HashMap<String, String>();
        int secretType = CredentialVaultService.SECRET_TYPE_USERID_STRING_PASSWORD_STRING;
        boolean bActive = false;
        boolean bPrivate = false;
     
        //Creating slot
        CredentialSlotConfig slot= vaultService.createCredentialSlot(resourceName, segmentID,descriptionsMap,
            keywordsMap, secretType, bActive, bPrivate, request);
        return slot.getSlotId();
    }


5. Getting SlotID: The following method retrieves slot ID. It iterates through all accessible slots and finds matching shared slot.

Listing 5
private String getSharedSlotId(PortletRequest request)
    {
        String slotId=null;
        try
        {
            for(Iterator it = vaultService.getAccessibleSlots(request); it.hasNext();)
            {
                CredentialSlotConfig config = (CredentialSlotConfig)it.next();
                if(config.getResourceName().startsWith(sharedSlotResourceName))
                {
                    slotId = config.getSlotId();
                    return slotId;
                }
            }

        }
        catch(CredentialVaultException e)
        {
            System.out.println("Exception while retrieveing slot id " + e);
        }
        return slotId;
    }


6. Retrieving Credentials: The following method retrieves shared passive credentials for the slot ID that matches resource name defined in portlet.xml

Listing 6
private void getCredential(RenderRequest request,StringBuffer userid, StringBuffer password) {
        try{
            String slotId = getSharedSlotId(request);

             if(slotId==null)
                 return ;

             UserPasswordPassiveCredential credential =(UserPasswordPassiveCredential) vaultService.getCredential
                        (slotId, "UserPasswordPassive", new HashMap<String,String>(), request);
               userid.append(credential.getUserId() );
               password.append( String.valueOf(credential.getPassword() ) );
        }
        catch(Exception  e){
                 return ;
          }
       }

7. Storing credentails: When a user submits form in edit mode, the following processAction is invoked. This method will check if the vault slot is already created. If it is not created, it will use createSlot method explained in step 4 to create vault slot. Then, it will set received userid and password into the credential vault slot.

Listing 7
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
       
        String userid = request.getParameter("userid");
        String password = request.getParameter("password");
        //If either userid or password is empty, show the user edit screen again
          if(userid == null || password == null || userid.trim().equals("")
                       || password.trim().equals(""))
              return;
         
          response.setPortletMode(PortletMode.VIEW); //Change from edit mode to view mode         
          try{
              String slotId = getSharedSlotId(request);
              if(slotId==null) { // Create slot if it is not already created
                  slotId = createSlot(request);
              }
              // Storing userid and password into the slot
              vaultService.setCredentialSecretUserPassword(slotId, userid,
                  password.toCharArray(),request);
          }
          catch(Exception e){
            System.out.println("Exception while creating slot or setting credentials " + e);
          }        
    }

8. Display Credentials: The following doView method  displays message to enter userid and password if the credentials are not set using edit mode. If the credentials are already set in the vault slot it will call getCredential  method described step 4 to get stored userid and password

Listing 8
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
   
        response.setContentType(request.getResponseContentType());

        PrintWriter writer = response.getWriter();
        StringBuffer userid= new StringBuffer("");
        StringBuffer password= new StringBuffer("");

          try{
            getCredential(request, userid, password);
                                               
            if(userid.toString().equals("") ){
                writer.println("There is no userid and password in shared vault slot." +
 " Please use <i>Personalize</i> mode to set them.<br>");        
            }
            else{
                writer.println("The UserID is  <strong>" + userid.toString() + "</strong><br>");
                writer.println("The Password is <strong>"  + password.toString() + "</strong><br>" );
            }
          }
          catch(Exception e){
              writer.println("Failed to get userid and password" + e);
              System.out.println("Exception happened while getting credentials " + e);
        }    
    }

9. Displaying edit mode contents: The following doEdit method displays  contents from editMode.jsp

Listing 9
public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
       
        PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("/jsp/editMode.jsp");
        rd.include(request,response);
       
    }

10.editMode.jsp: The following JSP shows  a screen for user to enter userid and password. This is included in edit mode

Listing 10
%@page session="false" contentType="text/html" pageEncoding="ISO-8859-1" import="java.util.*,javax.portlet.*" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>               
<portlet:defineObjects/>       
<style type="text/css">
.cssform p{
width: 300px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 150px;
height: 1%;
}

.cssform label{
font-weight: bold;
float: left;
margin-left: -150px;
width: 140px;
}

.cssform input[type="text"]{
width: 150px;
}
</style>

<FORM class="cssform" ACTION="<portlet:actionURL/>" METHOD="POST">

 <h3> Enter UserID and Password to Store into Shared Credential Vault Slot</h3>
    <p>
    <label>UserID:</label>
        <input type="text" name="userid" size="15" value=""> <br>
    </p>
    <p>
     <label> Password:</label>
     
      <input type="text" name="password" size="15" value=""><br>
    </p>   
      <input type="submit"  value="submit" size=35>&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;
      <input type="button"  onclick="window.location.href='<portlet:renderURL portletMode="view"/>'" value="cancel" size=35>         
</form>


Conclusion
This article demonstrated  on how to use credential vault APIs to store passive credential into vault slot of type shared. The article provided all the source code of portlet and JSP. The following attachment provides complete portlet code packaged in WAR file.      

ċ
UsingSharedSlot.war
(10k)
Sukumar Konduru,
Apr 21, 2009, 7:36 PM
Comments