The Java EE 5 Tutorial

Example: Using the isCallerInRole and getCallerPrincipal Methods

This example demonstrates how to use the getCallerPrincipal() and isCallerInRole(String role) methods with an enterprise bean. This example starts with a very simple EJB application, converter, and modifies the methods of the ConverterBean so that currency conversion will only occur when the requester is in the role of BeanUser.

For this tutorial, you will add the security elements to an enterprise bean; add the security elements to the deployment descriptor; build, package, and deploy the application; and then build and run the client application. The completed version of this example can be found at tut-install/javaeetutorial5/examples/ejb/converter-secure. This example was developed by starting with the unsecured enterprise bean application, converter, which is discussed in Chapter 21, Getting Started with Enterprise Beans and is found in the directory tut-install/javaeetutorial5/examples/ejb/converter/. This section builds on this example by adding the necessary elements to secure the application using the getCallerPrincipal() and isCallerInRole(String role) methods, which are discussed in more detail in Accessing an Enterprise Bean Caller’s Security Context.

    In general, the following steps are necessary when using the getCallerPrincipal() and isCallerInRole(String role) methods with an enterprise bean. In the example application included with this tutorial, many of these steps have been completed for you and are listed here simply to show what needs to be done should you wish to create a similar application.

  1. Create a simple enterprise bean application, such as the converter example. See Chapter 21, Getting Started with Enterprise Beans for more information on creating and understanding this example. This section of the tutorial starts with this unsecured application and demonstrates how to access an enterprise bean caller’s security context. The completed example application discussed in this section can be found at tut-install/javaeetutorial5/examples/ejb/converter-secure/.

  2. If you have not already done so, follow the steps in Building the Examples to set properties specific to your installation.

  3. If you have not already done so, set up a user on the Application Server in the file realm. Make sure that the user is included in the group named user. For information on adding a user to the file realm, read Managing Users and Groups on the Application Server.

  4. Modify ConverterBean to add the getCallerPrincipal() and isCallerInRole(String role) methods. For this example, callers that are in the role of BeanUser will be able to calculate the currency conversion. Callers not in the role of BeanUser will see a value of zero for the conversion amount. Modifying the ConverterBean code is discussed in Modifying ConverterBean.

  5. Modify the sun-ejb-jar.xml file to specify a secure connection, username-password login, and security role mapping. Modifying the sun-ejb-jar.xml file is discussed in Modifying Runtime Properties for the Secure Converter Example.

  6. Build, package, deploy, and run the application. These steps are discussed in Building, Deploying, and Running the Secure Converter Example Using NetBeans IDE and Building, Deploying, and Running the Secure Converter Example Using Ant.

  7. If necessary, refer to the tips in Troubleshooting the Secure Converter Application for tips on errors you might encounter and some possible solutions.

Modifying ConverterBean

The source code for the original converter application was modified as shown in the following code snippet (modifications in bold) to add the if..else clause that tests if the caller is in the role of BeanUser. If the user is in the correct role, the currency conversion is computed and displayed. If the user is not in the correct role, the computation is not performed, and the application displays the result as 0. The code example can be found in the following file:

tut-install/javaeetutorial5/examples/ejb/converter-secure/converter-secure-ejb/src/java/
converter/secure/ejb/ConverterBean.java

The code snippet is as follows:

package converter.secure.ejb;

import java.math.BigDecimal;
import javax.ejb.*;
import java.security.Principal;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
@Stateless()
@DeclareRoles("BeanUser")
public class ConverterBean implements converter.secure.ejb.Converter {
    @Resource SessionContext ctx;
    private BigDecimal yenRate = new BigDecimal("115.3100");
    private BigDecimal euroRate = new BigDecimal("0.0071");

    @RolesAllowed("BeanUser")
     public BigDecimal dollarToYen(BigDecimal dollars) {
        BigDecimal result = new BigDecimal("0.0");
        Principal callerPrincipal = ctx.getCallerPrincipal();
        if (ctx.isCallerInRole("BeanUser")) {
            result = dollars.multiply(yenRate);
            return result.setScale(2, BigDecimal.ROUND_UP);
        }else{
            return result.setScale(2, BigDecimal.ROUND_UP);
        }
        }
    @RolesAllowed("BeanUser")
    public BigDecimal yenToEuro(BigDecimal yen) {
        BigDecimal result = new BigDecimal("0.0");
        Principal callerPrincipal = ctx.getCallerPrincipal();
         if (ctx.isCallerInRole("BeanUser")) {
             result = yen.multiply(euroRate);
             return result.setScale(2, BigDecimal.ROUND_UP);
        }else{
            return result.setScale(2, BigDecimal.ROUND_UP);
        }
    }
}

Modifying Runtime Properties for the Secure Converter Example

Secure connections, username-password login, and the mapping of application roles to Application Server groups and principals are specified in the runtime deployment descriptor file sun-ejb-jar.xml. The original converter application that did not include any security mechanisms did not have a need for this file: it has been added specifically for this application.

To map the role of BeanUser that is defined for this application to the group with the name of user in the file realm of the Application Server, specify the security-role-mapping element as shown below. Make sure that the role-name and group-name elements are specified exactly as they are used (the mapping is case-sensitive).

To specify username-password login and a secure connection, use the ior-security-config element. The IOR security elements are described in more detail in Configuring IOR Security.

The following sun-ejb-jar.xml file demonstrates how to specify a secure connection, username-password login, and security role mapping. The completed version of this file can be found in tut-install/javaeetutorial5/examples/ejb/converter-secure/converter-secure-ejb/src/conf/sun-ejb-jar.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-ejb-jar PUBLIC 
"-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN" 
"http://www.sun.com/software/appserver/dtds/sun-ejb-jar_3_0-0.dtd">
<sun-ejb-jar>

    <security-role-mapping>
        <role-name>BeanUser</role-name>
        <group-name>user</group-name>
    </security-role-mapping>

     <enterprise-beans>
        <unique-id>0</unique-id>
        <ejb>
            <ejb-name>ConverterBean</ejb-name>
            <jndi-name>ConverterBean</jndi-name>
            <pass-by-reference>false</pass-by-reference>
            <ior-security-config>
                 <transport-config>
                    <integrity>supported</integrity>
                    <confidentiality>supported</confidentiality>
                    <establish-trust-in-target>
                        supported
                    </establish-trust-in-target>
                     <establish-trust-in-client>
                        supported
                    </establish-trust-in-client>
                     </transport-config>
                 <as-context>
                    <auth-method>username_password</auth-method>
                    <realm>file</realm>
                    <required>true</required>
                </as-context>
                <sas-context>
                    <caller-propagation>
                        supported
                    </caller-propagation>
                </sas-context>
                </ior-security-config>
                <is-read-only-bean>false</is-read-only-bean>
                <refresh-period-in-seconds>
                    -1
                </refresh-period-in-seconds>
                <gen-classes/>
            </ejb>
    </enterprise-beans>
 </sun-ejb-jar

Building, Deploying, and Running the Secure Converter Example Using NetBeans IDE

    Follow these instructions to build, package, and deploy the converter-secure example to your Application Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/ejb/.

  3. Select the converter-secure folder.

  4. Select the Open as Main Project and Open Required Projects check boxes.

  5. Click Open Project.

  6. In the Projects tab, right-click the converter-secure project and select Clean and Build.

  7. In the Projects tab, right-click the converter-secure project and select Undeploy and Deploy.

    This step builds and packages the application into converter-secure.ear, located in tut-install/javaeetutorial5/examples/ejb/converter-secure/dist/, and deploys this ear file to your Application Server instance.

  8. To run the secure converter’s application client, select Run->Run Main Project. You will be prompted for your username and password.

  9. Enter the username and password of a user that has been entered into the database of users for the file realm and has been assigned to the group of user.

    If the username and password you enter are authorized, you will see the output of the application client in the Output pane:


    [exec] $100.00 is 11531.00 Yen.
    [exec] 11531.00 Yen is 81.88 Euro.

Building, Deploying, and Running the Secure Converter Example Using Ant

    To build the secure converter enterprise beans and client, package and deploy the enterprise application, and run the client application, follow these steps:

  1. Set up your system for running the tutorial examples if you haven’t done so already by following the instructions in Building the Examples.

  2. From a terminal window or command prompt, go to the tut-install/javaeetutorial5/examples/ejb/converter-secure/ directory.

  3. Build, package, deploy, and run the enterprise application and application client by entering the following at the terminal window or command prompt in the ejb/converter-secure/ directory:


    ant all
    

    Note –

    This step assumes that you have the executable for ant in your path; if not, you will need to provide the fully qualified path to the ant executable. This command runs the ant target named all in the build.xml file.


The running application will look like this:


appclient-command-common:

At this point, a system login dialog will display. Enter the user name and password that correspond to a user in the group user on the Application Server. If the user name and password are authenticated, the following text displays in the terminal window or command prompt:


appclient-command-common:
    [exec] $100.00 is 11531.00 Yen.
    [exec] 11531.00 Yen is 81.88 Euro.

Troubleshooting the Secure Converter Application

Problem: The application displays zero values after authentication, as shown here:


appclient-command-common:
    [exec] $100.00 is 0.00 Yen.
    [exec] 0.00 Yen is 0.00 Euro.

Solution: Verify that the user name and password that you entered for authentication match a user name and password in the Application Server, and that this user is assigned to the group named user. User names and passwords are case-sensitive. Read Adding Users to the Application Server for more information on adding users to the file realm of the Application Server.