The Java EE 6 Tutorial, Volume I

Securing Enterprise Beans

Enterprise beans are Java EE components that implement Enterprise JavaBeans (EJB) technology. Enterprise beans run in the EJB container, a runtime environment within the Enterprise Server. Although transparent to the application developer, the EJB container provides system-level services such as transactions and security to its enterprise beans, which form the core of transactional Java EE applications.

Enterprise bean methods can be secured using one of the following methods:

Some of the material in this chapter assumes that you have already read Chapter 23, Introduction to Security in the Java EE Platform, Chapter 14, Enterprise Beans, and Chapter 15, Getting Started with Enterprise Beans.

As mentioned earlier, enterprise beans run in the EJB container, a runtime environment within the Enterprise Server, as shown in Figure 24–1.

Figure 24–1 Java EE Server and Containers

Diagram of Java EE server showing web container and EJB
container

This section discusses how to secure a Java EE application where one or more modules (such as EJB JAR files) are packaged into an EAR file, the archive file that holds the application. Security annotations will be used in the Java programming class files to specify authorized users and basic, or username-password, authentication.

Enterprise beans often provide the business logic of a web application. In these cases, packaging the enterprise bean within the web application's WAR module simplifies deployment and application organization. Enterprise beans may be packaged within a WAR module as Java programming language class files or within a JAR file that is bundled within the WAR module. When a servlet or JSP page handles the web front-end, and the application is packaged into a WAR module as a Java programming class file, then security for the application can be handled in the application's web.xml file. The EJB in the WAR file can have its own deployment descriptor, ejb-jar.xml, if required. Securing web applications using web.xml is discussed in Chapter 25, Getting Started Securing Web Applications and Part VII, Security, in The Java EE 6 Tutorial, Volume II.

The following sections describe declarative and programmatic security mechanisms that can be used to protect enterprise bean resources. The protected resources include methods of enterprise beans that are called from application clients, web components, or other enterprise beans.

You can protect enterprise beans by doing the following:

You should also read JSR-318: Enterprise JavaBeans 3.1 for more information on this topic. This document can be downloaded from http://jcp.org/en/jsr/detail?id=318. Chapter 17 of this specification, Security Management, discusses security management for enterprise beans.

Securing an Enterprise Bean Using Declarative Security and Annotations

Declarative security enables the application developer to specify which users are authorized to access which methods of the enterprise beans, and to authenticate these users with basic, or username-password, authentication.

Frequently, the person who is developing an enterprise application is not the same person who is responsible for deploying the application. When an application developer uses declarative security to define method permissions and authentications mechanisms, they are passing along to the deployer a security view of the enterprise beans contained in the EJB JAR. When a security view is passed on to the deployer, the deployer uses this information to define method permissions for security roles. If you don’t define a security view, the deployer will have to determine what each business method does to determine which users are authorized to call each method.

A security view consists of a set of security roles, a semantic grouping of permissions that a given type of users of an application must have to successfully access the application. Security roles are meant to be logical roles, representing a type of user. You can define method permissions for each security role. A method permission is a permission to invoke a specified group of methods of the enterprise beans’ business interface, home interface, component interface, and/or web service endpoints. After method permissions are defined, username-password authentication will be used to verify the identity of the user.

It is important to keep in mind that security roles are used to define the logical security view of an application. They should not be confused with the user groups, users, principals, and other concepts that exist in the Enterprise Server. An additional step is required to map the roles defined in the application to users, groups, and principals that are the components of the user database in the file realm of the Enterprise Server. These steps are outlined in Mapping Security Roles to Enterprise Server Groups.

The following sections show how an application developer uses declarative security to either secure an application or to create a security view to pass along to the deployer.

Specifying Authorized Users by Declaring Security Roles

This section discusses how to use annotations to specify the method permissions for the methods of a bean class. If you'd like more information on these annotations, refer to JSR-250 Common Annotations for the Java Platform.

Method permissions can be specified on the class, the business methods of the class, or both. Method permissions can be specified on a method of the bean class to override the method permissions value specified on the entire bean class. The following annotations are used to specify method permissions:


Example 24–1 Declaring Roles using @DeclareRoles

The following code snippet demonstrates the use of the @DeclareRoles annotation with the isCallerInRole method. In this example, the @DeclareRoles annotation declares a role that the enterprise bean PayrollBean uses to make the security check using isCallerInRole("payroll") to verify that the caller is authorized to change salary data.

@DeclareRoles("payroll")
@Stateless public class PayrollBean implements Payroll {
    @Resource SessionContext ctx;

    public void updateEmployeeInfo(EmplInfo info) {

        oldInfo = ... read from database;

        // The salary field can be changed only by callers
        // who have the security role "payroll"
        if (info.salary != oldInfo.salary &&
            !ctx.isCallerInRole("payroll")) {
                throw new SecurityException(...);
        }
        ...
    }
    ...
}


Example 24–2 Declaring Roles using @RolesAllowed

The following example code illustrates the use of the RolesAllowed annotation:

@RolesAllowed("admin")
public class SomeClass {
    public void aMethod () {...}
    public void bMethod () {...}
    ...
}

@Stateless public class MyBean extends SomeClass implements A  {

    @RolesAllowed("HR")
    public void aMethod () {...}

    public void cMethod () {...}
    ...
}

In this example, assuming aMethod, bMethod, and cMethod are methods of business interface A, the method permissions values of methods aMethod and bMethod are @RolesAllowed("HR") and @RolesAllowed("admin") respectively. The method permissions for method cMethod have not been specified.

To clarify, the annotations are not inherited by the subclass per se, they apply to methods of the superclass which are inherited by the subclass.


Mapping Security Roles to Enterprise Server Groups

The Enterprise Server assigns users to principals or groups, rather than to security roles. When you are developing a Java EE application, you don’t need to know what categories of users have been defined for the realm in which the application will be run. In the Java EE platform, the security architecture provides a mechanism for mapping the security roles defined in the application to the users, principals, or groups defined in the runtime realm. The deployer will work with the security view provided by the application developer to implement this mapping.

One way to declare a mapping between a security role used in the application and one or more groups and/or principals defined for the applicable realm of the Enterprise Server is to use the security-role-mapping element in the runtime deployment descriptor (sun-application.xml, sun-web.xml, or sun-ejb-jar.xml.) This is the method to use when the role name defined in the application does not match the group or principal name defined for the Enterprise Server. An example of this role mapping can be found in Part VII, Security, in The Java EE 6 Tutorial, Volume II.

    In the tutorial, the role names used in the application are the same as the group names defined on the Enterprise Server. Under these circumstances, you can enable a default principal-to-role mapping on the Enterprise Server using the Admin Console. To enable the default principal-to-role-mapping, follow these steps:

  1. Start the Enterprise Server, then the Admin Console.

  2. Expand the Configuration node.

  3. Select the Security node.

  4. On the Security page, check the Enabled box beside Default Principal to Role Mapping.

Specifying an Authentication Mechanism and Secure Connection

When method permissions are specified, basic, username-password, authentication will be invoked by the Enterprise Server.

If you would like to specify a different type of authentication, or to require a secure connection using SSL, you would specify this information in an application deployment descriptor. Using application deployment descriptors is discussed in Part VII, Security, in The Java EE 6 Tutorial, Volume II.

Example: Securing an Enterprise Bean

This section discusses how to configure an enterprise bean for username-password authentication. When a bean that is constrained in this way is requested, the server requests a user name and password from the client and verifies that the user name and password are valid by comparing them against a database of authorized users on the Enterprise Server.

If the topic of authentication is new to you, please refer to the section titled Specifying an Authentication Mechanism.

This example demonstrates security by starting with the unsecured enterprise bean application, cart, which is found in the directory tut-install/examples/ejb/cart/ and is discussed in The cart Example.

    In general, the following steps are necessary to add username-password authentication to an existing application that contains an enterprise bean.

  1. Create an application like the one in The cart Example.

  2. If you have not already done so, complete the steps inSetting Up Your System for Running the Security Examples to configure your system for running the tutorial applications.

  3. Modify the source code for the enterprise bean, CartBean.java, to specify which roles are authorized to access which protected methods. This step is discussed in Annotating the Bean.

  4. Build, package, and deploy the enterprise bean, then build and run the client application by following the steps in Building, Deploying, and Running the Secure Cart Example Using NetBeans IDE or Building, Deploying, and Running the Secure Cart Example Using Ant.

Annotating the Bean

The source code for the original cart application was modified as shown in the following code snippet (modifications in bold, method details are removed to save space). The resulting file can be found in the following location:

tut-install/examples/ejb/cart-secure/cart-secure-ejb/src/java/cart/
ejb/CartBean.java

The code snippet is as follows:

package cart.ejb;

import cart.util.BookException;
import cart.util.IdVerifier;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.annotation.security.RolesAllowed;

@Stateful
public class CartBean implements Cart {

    String customerName;
    String customerId;
    List<String> contents;

    public void initialize(String person) throws BookException {
        if (person == null) {
            throw new BookException("Null person not allowed.");
        } else {
            customerName = person;
        }

        customerId = "0";
        contents = new ArrayList<String>();
    }

    public void initialize(String person, String id) throws BookException {
        if (person == null) {
            throw new BookException("Null person not allowed.");
        } else {
            customerName = person;
        }

        IdVerifier idChecker = new IdVerifier();

        if (idChecker.validate(id)) {
            customerId = id;
        } else {
            throw new BookException("Invalid id: " + id);
        }

        contents = new ArrayList<String>();
    }

    @RolesAllowed("TutorialUser")
    public void addBook(String title) {
        contents.add(title);
    }

    @RolesAllowed("TutorialUser")
    public void removeBook(String title) throws BookException {
        boolean result = contents.remove(title);
        if (result == false) {
            throw new BookException("\"" + title + "\" not in cart.");
        }
    }

    @RolesAllowed("TutorialUser")
    public List<String> getContents() {
        return contents;
    }

    @Remove()
    @RolesAllowed("TutorialUser")
    public void remove() {
        contents = null;
    }
}

The @RolesAllowed annotation is specified on methods for which you want to restrict access. In this example, only users in the role of TutorialUser will be allowed to add and remove books from the cart, and to list the contents of the cart. An @RolesAllowed annotation implicitly declares a role that will be referenced in the application; therefore, no @DeclareRoles annotation is required. The presence of the @RolesAllowed annotation also implicitly declares that authentication will be required for a user to access these methods. If no authentication method is specified in the deployment descriptor, the type of authentication will be username-password authentication.

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

Follow the instructions for building, deploying, and running the secure cart example by following the instructions in Building, Packaging, Deploying, and Running the cart Example,

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

Follow the instructions for building, deploying, and running the secure cart example by following the instructions in Building, Packaging, Deploying, and Running the cart Example. Enter your user name and password when prompted to do so.

Securing an Enterprise Bean Programmatically

Programmatic security is code that is embedded in a business method, is used to access a caller's identity programmatically, and uses this information to make security decisions within the method itself.

Accessing an Enterprise Bean Caller’s Security Context

In general, security management should be enforced by the container in a manner that is transparent to the enterprise beans’ business methods. The security API described in this section should be used only in the less frequent situations in which the enterprise bean business methods need to access the security context information, such as when you want to restrict access to a particular time of day.

The javax.ejb.EJBContext interface provides two methods that allow the bean provider to access security information about the enterprise bean’s caller.

You would use programmatic security in this way to dynamically control access to a method, for example, when you want to deny access except during a particular time of day. An example application that uses the getCallerPrincipal and isCallerInRole methods is described in Example: Using the isCallerInRole and getCallerPrincipal Methods.

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

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 TutorialUser. 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 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("TutorialUser")
public class ConverterBean{
    @Resource SessionContext ctx;
    private BigDecimal yenRate = new BigDecimal("96.0650");
    private BigDecimal euroRate = new BigDecimal("0.0078");

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

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

After you've made the changes to the enterprise bean, follow the instructions in Compiling, Packaging, and Running the converter Example.

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

After you've made the changes to the enterprise bean, follow the instructions in Compiling, Packaging, and Running the converter Example.

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 Enterprise Server, and that this user is assigned to the group named TutorialUser. User names and passwords are case-sensitive. Read Adding Users to the Enterprise Server for more information on adding users to the file realm of the Enterprise Server.

Propagating a Security Identity (Run-As)

You can specify whether a caller’s security identity should be used for the execution of specified methods of an enterprise bean, or whether a specific run-as identity should be used.

Figure 24–2 illustrates this concept.

Figure 24–2 Security Identity Propagation

Diagram of security identity propagation from client
to intermediate container to target container

In this illustration, an application client is making a call to an enterprise bean method in one EJB container. This enterprise bean method, in turn, makes a call to an enterprise bean method in another container. The security identity during the first call is the identity of the caller. The security identity during the second call can be any of the following options:

Configuring a Component’s Propagated Security Identity

You can configure an enterprise bean’s run-as, or propagated, security identity using the @RunAs annotation. The RunAs annotation defines the role of the application during execution in a Java EE container. It can be specified on a class, allowing developers to execute an application under a particular role. The role must map to the user/group information in the container's security realm. The RunAs annotation specifies the name of a security role as its parameter.

Here is some example code that demonstrates the use of the RunAs annotation.

@RunAs("Admin")
public class Calculator {
	//....
}

You will have to map the run-as role name to a given principal defined on the Enterprise Server if the given roles associate to more than one user principal. Mapping roles to principals is described in Part VII, Security, in The Java EE 6 Tutorial, Volume II.

Trust between Containers

When an enterprise bean is designed so that either the original caller identity or a designated identity is used to call a target bean, the target bean will receive the propagated identity only; it will not receive any authentication data.

There is no way for the target container to authenticate the propagated security identity. However, because the security identity is used in authorization checks (for example, method permissions or with the isCallerInRole() method), it is vitally important that the security identity be authentic. Because there is no authentication data available to authenticate the propagated identity, the target must trust that the calling container has propagated an authenticated security identity.

By default, the Enterprise Server is configured to trust identities that are propagated from different containers. Therefore, there are no special steps that you need to take to set up a trust relationship.

Deploying Secure Enterprise Beans

The deployer is responsible for ensuring that an assembled application is secure after it has been deployed in the target operational environment. If a security view has been provided to the deployer through the use of security annotations and/or a deployment descriptor, the security view is mapped to the mechanisms and policies used by the security domain in the target operational environment, which in this case is the Enterprise Server. If no security view is provided, the deployer must set up the appropriate security policy for the enterprise bean application.

Deployment information is specific to a web or application server. Please read the Sun GlassFish Enterprise Server v3 Application Deployment Guide for more information on deploying enterprise beans.

Accepting Unauthenticated Users

Web applications may accept unauthenticated web clients and allow these clients to make calls to the EJB container. The EJB specification requires a security credential for accessing EJB methods. Typically, the credential will be that of a generic unauthenticated user. The way you specify this credential is implementation-specific.

    In the Enterprise Server, you must specify the name and password that an unauthenticated user will use to log in by modifying the Enterprise Server using the Admin Console:

  1. Start the Enterprise Server, then the Admin Console.

  2. Expand the Configuration node.

  3. Select the Security node.

  4. On the Security page, set the Default Principal and Default Principal Password values.