Examples: Securing Enterprise Beans - The Java EE 6 Tutorial (original) (raw)
2. Using the Tutorial Examples
3. Getting Started with Web Applications
4. JavaServer Faces Technology
7. Using JavaServer Faces Technology in Web Pages
8. Using Converters, Listeners, and Validators
9. Developing with JavaServer Faces Technology
10. JavaServer Faces Technology: Advanced Concepts
11. Using Ajax with JavaServer Faces Technology
12. Composite Components: Advanced Topics and Example
13. Creating Custom UI Components and Other Custom Objects
14. Configuring JavaServer Faces Applications
16. Uploading Files with Java Servlet Technology
17. Internationalizing and Localizing Web Applications
18. Introduction to Web Services
19. Building Web Services with JAX-WS
20. Building RESTful Web Services with JAX-RS
21. JAX-RS: Advanced Topics and Example
23. Getting Started with Enterprise Beans
24. Running the Enterprise Bean Examples
25. A Message-Driven Bean Example
26. Using the Embedded Enterprise Bean Container
27. Using Asynchronous Method Invocation in Session Beans
Part V Contexts and Dependency Injection for the Java EE Platform
28. Introduction to Contexts and Dependency Injection for the Java EE Platform
29. Running the Basic Contexts and Dependency Injection Examples
30. Contexts and Dependency Injection for the Java EE Platform: Advanced Topics
31. Running the Advanced Contexts and Dependency Injection Examples
32. Introduction to the Java Persistence API
33. Running the Persistence Examples
34. The Java Persistence Query Language
35. Using the Criteria API to Create Queries
36. Creating and Using String-Based Criteria Queries
37. Controlling Concurrent Access to Entity Data with Locking
38. Using a Second-Level Cache with Java Persistence API Applications
39. Introduction to Security in the Java EE Platform
40. Getting Started Securing Web Applications
41. Getting Started Securing Enterprise Applications
Securing an Enterprise Bean Using Declarative Security
Specifying Authorized Users by Declaring Security Roles
Specifying an Authentication Mechanism and Secure Connection
Securing an Enterprise Bean Programmatically
Accessing an Enterprise Bean Caller's Security Context
Propagating a Security Identity (Run-As)
Configuring a Component's Propagated Security Identity
Deploying Secure Enterprise Beans
42. Java EE Security: Advanced Topics
Part VIII Java EE Supporting Technologies
43. Introduction to Java EE Supporting Technologies
45. Resources and Resource Adapters
46. The Resource Adapter Example
47. Java Message Service Concepts
48. Java Message Service Examples
49. Bean Validation: Advanced Topics
50. Using Java EE Interceptors
51. Duke's Bookstore Case Study Example
52. Duke's Tutoring Case Study Example
53. Duke's Forest Case Study Example
The following examples show how to secure enterprise beans using declarative and programmatic security.
The cart-secure Example: Securing an Enterprise Bean with Declarative Security
This section discusses how to configure an enterprise bean for basic user name/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 GlassFish Server.
If the topic of authentication is new to you, see Specifying Authentication Mechanisms.
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 user name/password authentication to an existing application that contains an enterprise bean. In the example application included with this tutorial, 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.
- Create an application like the one in The cart 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 at tut-install/examples/security/cart-secure/.
- If you have not already done so, complete the steps in To Set Up Your System for Running the Security Examples to configure your system for running the tutorial applications.
- 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.
- Build, package, and deploy the enterprise bean; then build and run the client application by following the steps in To Run the cart-secure Example Using NetBeans IDE or To Run the cart-secure 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). The resulting file can be found in tut-install/examples/security/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.DeclareRoles; import javax.annotation.security.RolesAllowed;
@Stateful @DeclareRoles("TutorialUser") public class CartBean implements Cart { List contents; String customerId; String customerName;
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. A @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 user name/password authentication.
To Run the cart-secure Example Using NetBeans IDE
- Follow the steps in To Set Up Your System for Running the Security Examples.
- In NetBeans IDE, from the File menu, choose Open Project.
- In the Open Project dialog, navigate to:
tut-install/examples/security/ - Select the cart-secure folder.
- Select the Open as Main Project and Open Required Projects check boxes.
- Click Open Project.
- In the Projects tab, right-click the cart-secure project and select Build.
- In the Projects tab, right-click the cart-secure project and select Deploy.
This step builds and packages the application into cart-secure.ear, located in the directory_tut-install_/examples/security/cart-secure/dist/, and deploys this EAR file to your GlassFish Server instance. - To run the application client, right-click the cart-secure project and select Run.
A Login for user: dialog box appears. - In the dialog box, type the user name and password of a file realm user created on the GlassFish Server and assigned to the groupTutorialUser; then click OK.
If the user name and password you enter are authenticated, the output of the application client appears in the Output pane:
...
Retrieving book title from cart: Infinite Jest
Retrieving book title from cart: Bel Canto
Retrieving book title from cart: Kafka on the Shore
Removing "Gravity's Rainbow" from cart.
Caught a BookException: "Gravity's Rainbow" not in cart.
Java Result: 1
...
If the user name and password are not authenticated, the dialog box reappears until you type correct values.
To Run the cart-secure Example Using Ant
- Follow the steps in To Set Up Your System for Running the Security Examples.
- In a terminal window, go to:
tut-install/examples/security/cart-secure/ - To build the application and package it into an EAR file, type the following command at the terminal window or command prompt:
ant - To deploy the application to the GlassFish Server, type the following command:
ant deploy - To run the application client, type the following command:
ant run
This task retrieves the application client JAR and runs the application client.
A Login for user: dialog box appears. - In the dialog box, type the user name and password of a file realm user created on the GlassFish Server and assigned to the groupTutorialUser; then click OK.
If the user name and password are authenticated, the client displays the following output:
[echo] running application client container.
[exec] Retrieving book title from cart: Infinite Jest
[exec] Retrieving book title from cart: Bel Canto
[exec] Retrieving book title from cart: Kafka on the Shore
[exec] Removing "Gravity's Rainbow" from cart.
[exec] Caught a BookException: "Gravity's Rainbow" not in cart.
[exec] Result: 1
If the user name and password are not authenticated, the dialog box reappears until you type correct values.
The converter-secure Example: Securing an Enterprise Bean with Programmatic Security
This example demonstrates how to use the getCallerPrincipal and isCallerInRole 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 occur only when the requester is in the role of TutorialUser.
The completed version of this example can be found in the tut-install/examples/security/converter-securedirectory. This example is based on the unsecured enterprise bean application, converter, which is discussed in Chapter 23, Getting Started with Enterprise Beans and is found in the tut-install/examples/ejb/converter/ directory. This section builds on the example by adding the necessary elements to secure the application by using the getCallerPrincipal and isCallerInRole 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 andisCallerInRole 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.
- Create a simple enterprise bean application.
- Set up a user on the GlassFish Server in the file realm, in the group TutorialUser, and set up default principal to role mapping. To do this, follow the steps in To Set Up Your System for Running the Security Examples.
- Modify the bean to add the getCallerPrincipal and isCallerInRole methods.
- If the application contains a web client that is a servlet, specify security for the servlet, as described in Specifying Security for Basic Authentication Using Annotations.
- Build, package, deploy, and run the application.
Modifying ConverterBean
The source code for the original ConverterBean class was modified to add theif..else clause that tests whether 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 example can be found in tut-install/examples/ejb/converter-secure/converter-secure-ejb/src/java/converter/ejb/ConverterBean.java.
The code snippet (with modifications shown in bold) is as follows:
package converter.ejb;
import java.math.BigDecimal; import javax.ejb.Stateless; 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("89.5094");
private BigDecimal euroRate = new BigDecimal("0.0081");
**@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);**
**}**
}
}
Modifying ConverterServlet
The following annotations specify security for the converter web client, ConverterServlet:
@WebServlet(name = "ConverterServlet", urlPatterns = {"/"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"TutorialUser"}))
To Build, Package, and Deploy the converter-secure Example Using NetBeans IDE
- Follow the steps in To Set Up Your System for Running the Security Examples.
- In NetBeans IDE, from the File menu, choose Open Project.
- In the Open Project dialog, navigate to:
tut-install/examples/security/ - Select the converter-secure folder.
- Select the Open as Main Project check box.
- Click Open Project.
- Right-click the converter-secure project and select Build.
- Right-click the converter-secure project and select Deploy.
To Build, Package, and Deploy the converter-secure Example Using Ant
- Follow the steps in To Set Up Your System for Running the Security Examples.
- In a terminal window, go to:
tut-install/examples/security/converter-secure/ - Type the following command:
ant all
This command both builds and deploys the example.
To Run the converter-secure Example
- Open a web browser to the following URL:
http://localhost:8080/converter-secure
An Authentication Required dialog box appears. - Type a user name and password combination that corresponds to a user who has already been created in the file realm of the GlassFish Server and has been assigned to the group of TutorialUser; then click OK.
- Type 100 in the input field and click Submit.
A second page appears, showing the converted values.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices