Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

Securing Enterprise Beans

Accessing an Enterprise Bean Caller's Security Context

Declaring Security Role Names Referenced from Enterprise Bean Code

Declaring Security Roles Using Annotations

Declaring Security Roles Using Deployment Descriptor Elements

Defining a Security View of Enterprise Beans

Defining Security Roles

Specifying an Authentication Mechanism

Specifying Method Permissions

Mapping Security Roles to Application Server Groups

Propagating Security Identity

Using Enterprise Bean Security Annotations

Using Enterprise Bean Security Deployment Descriptor Elements

Configuring IOR Security

Deploying Secure Enterprise Beans

Accepting Unauthenticated Users

Accessing Unprotected Enterprise Beans

Enterprise Bean Example Applications

Example: Securing an Enterprise Bean

Annotating the Bean

Setting Runtime Properties

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

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

Example: Using theisCallerInRole andgetCallerPrincipal Methods

ModifyingConverterBean

Modifying Runtime Properties for the Secure Converter Example

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

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

Troubleshooting the Secure Converter Application

Discussion: Securing the Duke's Bank Example

Securing Application Clients

Using Login Modules

Using Programmatic Login

Securing EIS Applications

Container-Managed Sign-On

Component-Managed Sign-On

Configuring Resource Adapter Security

Mapping an Application Principal to EIS Principals

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Enterprise Bean Example Applications

The following example applications demonstrate adding security to enterprise beans applications:

Example: Securing an Enterprise Bean

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

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

For this tutorial, you will add the security elements to an enterprise bean;add security elements to the deployment descriptors; build, package, and deploy the application;and then build and run the client application.

The completed version of this example can be found attut-install/javaeetutorial5/examples/ejb/cart-secure/. Thisexample was developed by starting with the unsecured enterprise bean application,cart, whichis found in the directorytut-install/javaeetutorial5/examples/ejb/cart/ and is discussed inThecart Example. You buildon this example by adding the necessary elements to secure the application usingusername-password authentication.

In general, the following steps are necessary to add username-password authentication to anenterprise bean. In the example application included with this tutorial, many of thesesteps have been completed for you and are listed here simply to showwhat needs to be done should you wish to create a similar application.

  1. Create an application like the one inThecart Example. The example in this tutorial starts with this example and demonstrates adding basic authentication of the client to this application. The example application discussed in this section can be found attut-install/javaeetutorial5/examples/ejb/cart-secure/.

  2. If you have not already done so, complete the steps inBuilding the Examples to configure your system properly for running the tutorial applications.

  3. If you have not already done so, add a user to thefile realm and specifyuser for the group of this new user. Write down the user name and password so that you can use them for testing this application in a later step. Refer to the sectionManaging Users and Groups on the Application Server for instructions on completing this step.

  4. 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 inAnnotating the Bean.

  5. Modify the runtime deployment descriptor,sun-ejb-jar.xml, to map the role used in this application (CartUser) to a group defined on the Application Server (user) and to add security elements that specify that username-password authentication is to be performed. This step is discussed inSetting Runtime Properties.

  6. Build, package, and deploy the enterprise bean, then build and run the client application by following the steps inBuilding, Deploying, and Running the Secure Cart Example Using NetBeans IDE orBuilding, Deploying, and Running the Secure Cart Example Using Ant.

Annotating the Bean

The source code for the originalcart application was modified as shown inthe following code snippet (modifications inbold, method details removed to savespace). The resulting file can be found in the following location:

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

The code snippet is as follows:

package com.sun.tutorial.javaee.ejb;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 {         ...        }    public void initialize(String person, String id) throws BookException {         ... }@RolesAllowed("CartUser")    public void addBook(String title) {        contents.add(title);    }@RolesAllowed("CartUser")    public void removeBook(String title) throws BookException {         ... }    }@RolesAllowed("CartUser")    public List<String> getContents() {        return contents;    }    @Remove()        public void remove() {        contents = null;    }}

The@RolesAllowed annotation is specified on methods for which you want to restrictaccess. In this example, only users in the role ofCartUser will beallowed to add and remove books from the cart, and to list thecontents of the cart. An@RolesAllowed annotation implicitly declares a role that willbe referenced in the application; therefore, no@DeclareRoles annotation is required.

Setting Runtime Properties

The role ofCartUser has been defined for this application, but there isno group ofCartUser defined for the Application Server. To map the rolethat is defined for the application (CartUser) to a group that is definedon the Application Server (user), add a<security-role-mapping> element to the runtime deployment descriptor,sun-ejb-jar.xml, as shown below. In the original example, there was no need forthis deployment descriptor, so it has been added for this example.

To enable username-password authentication for the application, add security elements to the runtimedeployment descriptor,sun-ejb-jar.xml. The security element that needs to be added tothe deployment descriptor is the <ior-security-config> element. The deployment descriptor is located intut-install/javaeetutorial5/examples/ejb/cart-secure/cart-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>CartUser</role-name>        <group-name>user</group-name>    </security-role-mapping>    <enterprise-beans>        <unique-id>0</unique-id>        <ejb>            <ejb-name>CartBean</ejb-name>            <jndi-name>jacc_mr_CartBean</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>default</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>

For more information on this topic, readSpecifying an Authentication Mechanism andConfiguring IOR Security.

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

Follow these instructions to build, deploy, and run thecart-secure example inyour Application Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

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

  3. Select thecart-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 thecart-secure project and select Clean and Build.

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

    This step builds and packages the application intocart-secure.ear, located intut-install/javaeetutorial5/examples/ejb/cart-secure/dist/, and deploys this ear file to your Application Server instance.

  8. To run secure cart’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 theoutput of the application client in the Output pane:

...Retrieving book title from cart: Infinite JestRetrieving book title from cart: Bel CantoRetrieving book title from cart: Kafka on the ShoreRemoving "Gravity’s Rainbow" from cart.Caught a BookException: "Gravity’s Rainbow" not in cart.Java Result: 1run-cart-secure-app-client:
Building, Deploying, and Running the Secure Cart Example Using Ant

To build, deploy, and run the secure EJB example using the Anttool, follow these steps:

  1. If you have not already done so, specify properties specific to your installation in thetut-install/javaeetutorial5/examples/bp-project/build.properties file and thetut-install/javaeetutorial5/examples/common/admin-password.txt file. SeeBuilding the Examples for information on which properties need to be set in which files.

  2. If you have not already done so, add a user to thefile realm and specifyuser for the group of this new user. Refer to the sectionManaging Users and Groups on the Application Server for instructions on completing this step.

  3. From a terminal window or command prompt, go to thetut-install/javaeetutorial5/examples/ejb/cart-secure/ directory.

  4. Build, package, and deploy the enterprise application, and build and run the client, by entering the following at the terminal window or command prompt in theejb/cart-secure/ directory:

    ant all

    Note -This step assumes that you have the executable forant in your path; if not, you will need to provide the fully qualified path to theant executable. This command runs theant target namedall in thebuild.xml file.


  5. A Login for User dialog displays. Enter a user name and password that correspond to a user set up on the Application Server with a group ofuser. Click OK.

If the user name and password are authenticated, the client displays the followingoutput:

run:    [echo] Running appclient for Cart.appclient-command-common:    [exec] Infinite Jest    [exec] Bel Canto    [exec] Kafka on the Shore    [exec] Caught a BookException: "Gravity’s Rainbow" not in cart.

If the username and password arenot authenticated, the client displays the followingerror:

run:    [echo] Running appclient for Cart.appclient-command-common:    [exec] Caught an unexpected exception!    [exec] javax.ejb.EJBException: nested exception is: java.rmi.AccessException:     CORBA NO_PERMISSION 9998 Maybe; nested exception is:    [exec]     org.omg.CORBA.NO_PERMISSION:     ----------BEGIN server-side stack trace----------    [exec] org.omg.CORBA.NO_PERMISSION:   vmcid: 0x2000  minor code: 1806

If you see this response, verify the user name and password ofthe user that you entered in the login dialog, make sure that useris assigned to the groupuser, and rerun the client application.

Example: Using theisCallerInRole andgetCallerPrincipal Methods

This example demonstrates how to use thegetCallerPrincipal() andisCallerInRole(String role) methods withan enterprise bean. This example starts with a very simple EJB application,converter, andmodifies the methods of theConverterBean so that currency conversion will only occurwhen the requester is in the role ofBeanUser.

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 theapplication; and then build and run the client application. The completed version ofthis example can be found attut-install/javaeetutorial5/examples/ejb/converter-secure. This example was developed bystarting with the unsecured enterprise bean application,converter, which is discussed inChapter 21, Getting Started with Enterprise Beansand is found in the directorytut-install/javaeetutorial5/examples/ejb/converter/. This section builds on this exampleby adding the necessary elements to secure the application using thegetCallerPrincipal() andisCallerInRole(String role) methods, which are discussed in more detail inAccessing an Enterprise Bean Caller's Security Context.

In general, the following steps are necessary when using thegetCallerPrincipal() andisCallerInRole(String role) methods with an enterprise bean. In the example application included with thistutorial, many of these steps have been completed for you and are listedhere simply to show what needs to be done should you wish tocreate a similar application.

  1. Create a simple enterprise bean application, such as theconverter example. SeeChapter 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 attut-install/javaeetutorial5/examples/ejb/converter-secure/.

  2. If you have not already done so, follow the steps inBuilding 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 thefile realm. Make sure that the user is included in the group nameduser. For information on adding a user to thefile realm, readManaging Users and Groups on the Application Server.

  4. ModifyConverterBean to add thegetCallerPrincipal() andisCallerInRole(String role) methods. For this example, callers that are in the role ofBeanUser will be able to calculate the currency conversion. Callers not in the role ofBeanUser will see a value of zero for the conversion amount. Modifying theConverterBean code is discussed inModifyingConverterBean.

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

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

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

ModifyingConverterBean

The source code for the originalconverter application was modified as shown inthe following code snippet (modifications inbold) to add theif..else clause thattests if the caller is in the role ofBeanUser. If the useris in the correct role, the currency conversion is computed and displayed. Ifthe user is not in the correct role, the computation is notperformed, and the application displays the result as0. The code example can befound 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 Servergroups and principals are specified in the runtime deployment descriptor filesun-ejb-jar.xml. Theoriginalconverter application that did not include any security mechanisms did not havea need for this file: it has been added specifically for this application.

To map the role ofBeanUser that is defined for this application tothe group with the name ofuser in the file realm of theApplication Server, specify thesecurity-role-mapping element as shown below. Make sure that therole-name andgroup-name elements are specified exactly as they are used (themapping is case-sensitive).

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

The followingsun-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 foundintut-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 theconverter-secure example toyour Application Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

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

  3. Select theconverter-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 theconverter-secure project and select Clean and Build.

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

    This step builds and packages the application intoconverter-secure.ear, located intut-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 theenterprise 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 inBuilding the Examples.

  2. From a terminal window or command prompt, go to thetut-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 theejb/converter-secure/ directory:

    ant all

    Note -This step assumes that you have the executable forant in your path; if not, you will need to provide the fully qualified path to theant executable. This command runs theant target namedall in thebuild.xml file.


The running application will look like this:

appclient-command-common:

At this point, a system login dialog will display. Enter the username and password that correspond to a user in the groupuser on theApplication Server. If the user name and password are authenticated, the following textdisplays 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 authenticationmatch a user name and password in the Application Server, and that thisuser is assigned to the group nameduser. User names and passwordsare case-sensitive. ReadAdding Users to the Application Server for more information on adding users to thefilerealm of the Application Server.

Discussion: Securing the Duke’s Bank Example

The Duke’s Bank application is an online banking application. Duke’s Bank has twoclients: an application client used by administrators to manage customers and accounts, anda web client used by customers to access account histories and perform transactions.The clients access the customer, account, and transaction information maintained in a databasethrough enterprise beans. The Duke’s Bank application demonstrates the way that many of thecomponent technologies presented in this tutorial (enterprise beans, application clients, and web components)are applied to provide a simple but functional application.

To secure the Duke’s Bank example, the following security mechanisms are used:

  • Defining security roles

  • Specifying form-based user authentication for the web client in a security constraint

  • Adding authorized users and groups to the appropriate Application Server realm

  • Specifying method permissions for enterprise beans

  • Configuring Interoperable Object References (IOR)

ReadChapter 37, The Duke's Bank Application for more information on securing the Duke’s Bank example.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp