10.3 Using active credentials

 < Day Day Up > 

After importing and testing the protected servlet, you will build a portlet application accessing the Treasure servlet and using active credential objects.The portlet will be created based on the Basic portlet type and will demonstrate the use of credentials. Once the project is created, you will run it in the WebSphere Portal Test Environment to view it.

Creating the Credential Vault portlet application

To create the new portlet project, follow these steps:

  1. Switch to the Portlet perspective ( Window -> Open Perspective ).

  2. Select File -> New -> Other .

    Figure 10-10. Invoking New Project wizard

    graphics/10fig10.jpg

  3. Select Portlet development -> Portlet application project . Click Next .

    Figure 10-11. Creating a new portlet application

    graphics/10fig11.jpg

  4. In the Define the Portlet Project page, enter a project name of CredVaultBasicAuth and click Next .

    Figure 10-12. Define the Portlet Project

    graphics/10fig12.jpg

  5. In the J2EE Settings Page, leave the defaults and click Next .

  6. In Portlet Settings, accept all values. Click Next .

  7. In Event Handling, uncheck Add form sample so that only Add action listener is checked. Click Next .

    Figure 10-13. Event Handling page of New Portlet Application wizard

    graphics/10fig13.jpg

  8. In the Single Sign-On page, check Add credential vault handling and enter a slot name of TreasureCredentialSlot . Click Next .

    Figure 10-14. Single Sign-On page of the new portlet application wizard

    graphics/10fig14.jpg

  9. Since no additional markups and no additional modes will be supported in this scenario, click Finish to generate the portlet. After a few minutes, the portlet deployment descriptor of the new portlet application opens.

Reviewing the generated code

Before the portlet code is modified to access the secure portlet, let's examine the wizard generated code.

If you expand the credvaultbasicauth package in the Source folder of the new project, you can see a CredVaultBasicAuthSecurityManager class in addition to the portlet and bean classes. This class is responsible for initializing the Credential Vault service and administering the credentials.

Figure 10-15. Reviewing CredVaultBasicAuthSecurityManager class

graphics/10fig15.jpg

The following methods are provided in this class to handle Credential Vault issues:

  • The init method of this class initializes the vaultService data member.

  • getCredential returns the user name and password by using a string buffer.

  • setCredential sets the user name and password.

  • getSlotld returns the ID of the slot. Depending on the type of slot, this method uses PortletData or VaultService to get the ID.

  • New slots are created in the createNewSlot method.

  • getPrincipalFromSubject retrieves the specified Principal from the provided subject.

  • isWritable checks whether the password can be saved.

The wizard has also created an input form for a user ID and password in the CredVaultBasicAuthPortletEdit.jsp. As previously described, when clicking the Save button, the actionPerformed() method in the portlet class is called. This method retrieves the user ID and password from the form and uses the security manager class to set the credentials.

The current version of the doView method retrieves the user credentials from the security manager and displays them in the JSP. Because we want to include the content of the secured Treasure servlet, we will replace this method in the next section of this scenario.

10.3.1 Updating the generated portlet

Modify the portlet application as follows :

  1. Open CredVaultBasicAuthPortletSecretManager from the credvaultbasicauth package.

  2. Using the Java editor, add the method shown in Example 10-1 to the class. The method can be found in the c:\LabFiles\CredentialVault\Snippets folder.

    Note : The sample scenario included in this chapter requires that you download the sample code available as additional materials. See Appendix C, "Additional material" on page 543.

    You may want to use WordPad to edit getConnectionUsingActiveObject.java and then copy and paste.

    Note : The getConnectionUsingActiveObject method returns an http connection.

    Example 10-1. getConnectionUsingActiveObject method (active credentials)
      public static HttpURLConnection getConnectionUsingActiveObject(   PortletRequest portletRequest,   CredVaultBasicAuthPortletSessionBean sessionBean,   String host, String port, String path) {   HttpURLConnection connection=null  ;  try {   URL urlSpec =   new URL("http://" + host + ":" + port + path)  ;  String slotId = getSlotId(portletRequest, sessionBean, false)  ;  if (slotId != null) {   HttpBasicAuthCredential credential =   (HttpBasicAuthCredential) vaultService.getCredential(   slotId,   "HttpBasicAuth",   new HashMap(),   portletRequest)  ;  connection = credential.getAuthenticatedConnection(urlSpec)  ;  }   } catch (Exception e) {   e.printStackTrace()  ;  }   return connection  ;  }  
  3. Some code errors appear because the required import statements are missing. To fix these errors, right-click the Java editor and select Source -> Organize Imports .

  4. In the Organize Imports dialog, choose

    1. java.net.HttpURLConnection

    2. select java.net.URL

    Click Finish to close the Organize Imports dialog.

    Figure 10-16. Importing missing import statements using Organize Imports tool

    graphics/10fig16.gif

  5. Save and close the Java file.

  6. Open the class CredVaultBasicAuthPortlet from the credvaultbasicauth package.

  7. Replace the doView method so it looks as shown in Example 10-2 on page 337. You may want to copy and paste from c:\LabFiles\CredentialVault\Snippets\doView.java.

    Note : The sample scenario included in this chapter requires that you download the sample code available as additional materials. See Appendix C, "Additional material" on page 543.

    Example 10-2. The doView method uses a Http connection from the SecretManager class
     public void  doView  (PortletRequest request, PortletResponse response)       throws PortletException, IOException {       // Check if portlet session exists       CredVaultBasicAuthPortletSessionBean sessionBean =          getSessionBean(request);       if (sessionBean == null) {          response.getWriter().println("<b>NO PORTLET SESSION YET</b>");          return;       }       // get output stream to write the results       PrintWriter writer = response.getWriter();       // get the CredentialVault PortletService       PortletContext context = this.getPortletConfig().getContext();       try {          String host = request.getServerName();          //String host = request.getRemoteHost();          String port = String.valueOf(request.getServerPort());          String path = "/TreasureWeb/TreasurePage";          HttpURLConnection connection =  CredVaultBasicAuthPortletSecretManager.getConnectionUsingActiveObject  (                 request, sessionBean, host, port, path );          if (connection != null) {             connection.connect();             String responseMessage =  connection.getResponseMessage();             int responseCode = connection.getResponseCode();             // Were we successful?             if (HttpURLConnection.HTTP_OK == responseCode) {                writer.println("<P>Successfully connected!</P>");             } else {                writer.println(                   "<P>Unable to successfully connect to back end."                      + ", HTTP Response Code = " + responseCode                      + ", HTTP Response Message = \"" + responseMessage                      + "\"</P>");           }           BufferedReader br =              new BufferedReader(                 new InputStreamReader(connection.getInputStream()));           String line;           while ((line = br.readLine()) != null)              writer.println(line + "\n");        } else {           writer.println(           "<h2>Credential not found. Please set it in the edit mode! </h2>");           return;          }        } catch (IOException exc) {           writer.println(              "<h2>Single-sign-on error, login at back-end failed! </h2>");           return;        }    } 
  8. Organize the import statements as you did before.

  9. Save and close the Java file.

Important : If you get a message indicating that getConnectionUsingActiveObject() is undefined, try making a small modification to the file and enabling the save option. Save the file again. This procedure should resolve any pending undefined issues.

10.3.2 Running the portlet

In this section, you will run the portlet using active credentials to access the back-end resource, a protected servlet in this case.

  1. Close any open browser viewers .

  2. Switch to the Portlet perspective.

  3. In the Server Configuration view, right-click the Servers folder and choose New -> Server and Server Configuration .

    Figure 10-17. Creation of a new server

    graphics/10fig17.jpg

  4. In the Server Selection dialog, choose a server of the WebSphere Portal V5.0 Test Environment and enter a server name of WPS 5.0 . Click Finish to add the new server.

    Figure 10-18. Create a new WebSphere Portal Test Environment

    graphics/10fig18.jpg

  5. Add the Treasure servlet to the portal test environment, right-click the WPS5.0 server and choose Add -> TreasureEAR .

    Figure 10-19. Add Treasure servlet and CredVault portlet to portal test environment

    graphics/10fig19.jpg

  6. Repeat the previous step to add the DefaultEAR to the portal Test Environment. This will also add the CredVaultBasicAuth portlet to the server.

  7. In the J2EE Navigator view select CredVaultBasicAuth , choose Run on server and wait a few minutes for the Portal server to open for e-business. This will start the server and will also open a browser displaying the portlet.

    Figure 10-20. Selecting Run on Server... to test the portlet.

    graphics/10fig20.jpg

  8. The portlet will execute the initConcrete method to initialize the Credential Vault Service and the doView method. Since there are no credentials yet, a message is displayed.

  9. Switch to the Edit mode and enter the following information:

    - User ID: user1

    - Password: password1

  10. Submit the action. This will generate an action that will be checked by the actionPerformed method in the CredVaultBasicAuthPortlet class. The portlet returns to View mode, showing the contents of the Treasure Servlet.

  11. In the Servers view, stop the running portal server.

    Figure 10-21. The CredentialVault portlet in action

    graphics/10fig21.gif

 < Day Day Up > 


IBM WebSphere Portal V5 A Guide for Portlet Application Development
IBM Websphere Portal V5: A Guide for Portlet Application Development
ISBN: 0738498513
EAN: 2147483647
Year: 2004
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net