Documentation‎ > ‎WebSphere Portal‎ > ‎

Using Private Credential Vault Slot in WebSphere Portal 6.1

Article

Introduction
This article analyzes sample portlet  that  uses private credential vault slot in WebSphere Portal 6.1. 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 checks if the vault slot is already created by checking for slotID from the preferences settings of user. If the slot is not already created, it will create private 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 invoke credential vault APIs to create vault slots, set credentials and retrieve credentials. Moreover, this article shows JSP used in edit mode of portlet.

1. 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 1

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

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.CredentialVaultService;
import com.ibm.portal.portlet.service.credentialvault.
               credentials.UserPasswordPassiveCredential;


2. 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.

Listing 2

 private static CredentialVaultService vaultService = null;

    public void init() throws PortletException{
        super.init();
       
        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);
        }
    }


3. Creating Slot: The following code creates credential vault slot and assigns slot ID into portlet preferences.  The vault slot is created as private by  passing bPrivate parameter as false and as passive credential by passing bActive parameter as false.

Listing 3


private String createSlot(ActionRequest request) throws Exception
    {
        PortletPreferences preferences = request.getPreferences();
        String resourceName = "BankApplication";
        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 = true;
     
        //Creating slot
        CredentialSlotConfig slot= vaultService.createCredentialSlot(resourceName, segmentID,descriptionsMap,
            keywordsMap, secretType, bActive, bPrivate, request);
         
        preferences.setValue("privateSlotID", slot.getSlotId());
        preferences.store();
        return slot.getSlotId();
    }


4. Retrieving Credentials:
The following method retrieves passive credentials from the slot ID set in portlet preferences for an attribute privateslotID.

Listing 4


private void getCredential(RenderRequest request,StringBuffer userid, StringBuffer password) {
        try{
            String slotId = (String) request.getPreferences().getValue("privateSlotID", null);

             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 ;
          }
       }


5. Storing credentails: When a user submits HTML form in edit mode, the following processAction method 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 3 to create vault slot. Then, it will set received userid and password into the credential vault slot.

Listing 5

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{
              PortletPreferences preferences = request.getPreferences();
              String slotId = (String) preferences.getValue("privateSlotID",null);
                    
              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("The exception is " + e);
          }        
    }

6. 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 6

 
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 private 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 " + e);
        }    
    }



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

Listing 7


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


8.editMode.jsp: The following JSP shows  a screen for user to enter userid and password. This JSP  is included from the doEdit method.


Listing 8

 
<%@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 Private 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 private. The article provided all the source code of portlet and JSP. The code can be used to develop complete portlet to exploit private credential vault slot. The following attachment provides complete portlet code.      




ċ
UsingPrivateSlot.war
(10k)
Sukumar Konduru,
Apr 17, 2009, 4:24 PM
Comments