2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 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 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 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 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 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 Specifying an Authentication Mechanism Mapping Security Roles to Application Server Groups Using Enterprise Bean Security Annotations Using Enterprise Bean Security Deployment Descriptor Elements Deploying Secure Enterprise Beans Enterprise Bean Example Applications Example: Securing an Enterprise Bean 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 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 Configuring Resource Adapter Security Mapping an Application Principal to EIS Principals 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Securing Enterprise BeansEnterprise beans are the Java EE components that implement Enterprise JavaBeans (EJB) technology.Enterprise beans run in the EJB container, a runtime environment within the ApplicationServer, as shown inFigure 29-1. Figure 29-1 Java EE Server and Containers ![]() Although transparent to the application developer, the EJB container provides system-level services suchas transactions and security to its enterprise beans. These services enable you toquickly build and deploy enterprise beans, which form the core of transactional JavaEE applications. The following sections describe declarative and programmatic security mechanisms that can be usedto protect enterprise bean resources.The protected resources include methods of enterprise beans that are called from application clients,web components, or other enterprise beans. This section assumes that you have readChapter 20, Enterprise Beans andChapter 21, Getting Started with Enterprise Beans before starting this section. You can protect enterprise beans by doing the following:
Two example applications demonstrate adding security to enterprise beans. These example applications arediscussed in the following sections: You should also readJSR-220: Enterprise JavaBeans 3.0 for more information on this topic. This documentcan be downloaded fromhttp://jcp.org/en/jsr/detail?id=220. Chapter 16 of this specification,Security Management, discusses security managementfor enterprise beans. Accessing an Enterprise Bean Caller’s Security ContextIn general, security management should be enforced by the container in a mannerthat is transparent to the enterprise beans’ business methods. The security API describedin this section should be used only in the less frequent situations inwhich the enterprise bean business methods need to access the security context information. Thejavax.ejb.EJBContext interface provides two methods that allow the bean provider to accesssecurity information about the enterprise bean’s caller.
The following code sample illustrates the use of thegetCallerPrincipal() method: @Stateless public class EmployeeServiceBean implements EmployeeService{ @Resource SessionContext ctx; @PersistenceContext EntityManager em; public void changePhoneNumber(...) { ... // obtain the caller principal. callerPrincipal = ctx.getCallerPrincipal(); // obtain the caller principal’s name. callerKey = callerPrincipal.getName(); // use callerKey as primary key to find EmployeeRecord EmployeeRecord myEmployeeRecord = em.findByPrimaryKey(EmployeeRecord.class, callerKey); // update phone number myEmployeeRecord.setPhoneNumber(...); ... }}In the previous example, the enterprise bean obtains the principal name of thecurrent caller and uses it as the primary key to locate anEmployeeRecord entity. This example assumes that application has been deployed such that thecurrent caller principal contains the primary key used for the identification of employees(for example, employee number). The following code sample illustrates the use of theisCallerInRole(String roleName) method: @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(...); } ... } ... }An example application that uses thegetCallerPrincipal andisCallerInRole methods is describedinExample: Using theisCallerInRole andgetCallerPrincipal Methods. Declaring Security Role Names Referenced from Enterprise Bean CodeYou can declare security role names used in enterprise bean code using eitherthe@DeclareRoles annotation (preferred) or thesecurity-role-ref elements of the deployment descriptor. Declaring securityrole names in this way enables you to link these security role namesused in the code to the security roles defined for an assembled application.In the absence of this linking step, any security role name used inthe code will be assumed to correspond to a security role ofthe same name in the assembled application. A security role reference, including the name defined by the reference, is scopedto the component whose bean class contains the@DeclareRoles annotation or whose deploymentdescriptor element contains thesecurity-role-ref deployment descriptor element. You can also use thesecurity-role-ref elements for those references that were declaredin annotations and you want to have linked to asecurity-role whose namediffers from the reference value. If a security role reference is not linkedto a security role in this way, the container must map the referencename to the security role of the same name. SeeLinking Security Role References to Security Roles for adescription of how security role references are linked to security roles. For an example using each of these methods, read the following sections: Declaring Security Roles Using AnnotationsThe@DeclareRoles annotation is specified on a bean class, where it serves todeclare roles that can be tested by callingisCallerInRole from within themethods of the annotated class. You declare the security roles referenced in the code using the@DeclareRoles annotation.When declaring the name of a role used as a parameter to theisCallerInRole(String roleName) method, the declared name must be the same as the parameter value.You can optionally provide a description of the named security roles in thedescription element of the@DeclareRoles annotation. The following code snippet demonstrates the use of the@DeclareRoles annotation. Inthis example, the@DeclareRoles annotation indicates that the enterprise beanAardvarkPayroll makes the securitycheck usingisCallerInRole("payroll") to verify that the caller is authorized to change salarydata. The security role reference is scoped to the session or entity beanwhose declaration contains the@DeclareRoles annotation. @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(...); } ... } ...}The syntax for declaring more than one role is as shown inthe following example: @DeclareRoles({"Administrator", "Manager", "Employee"})Declaring Security Roles Using Deployment Descriptor ElementsNote -Any values explicitly specified in the deployment descriptor override any values specified inannotations. If a value for a method has not been specified in thedeployment descriptor, and a value has been specified for that method by meansof the use of annotations, the value specified in annotations will apply. Thegranularity of overriding is on the per-method basis. If the@DeclareRoles annotation is not used, you can use thesecurity-role-ref elementsof the deployment descriptor to declare the security roles referenced in the code,as follows:
The following example illustrates how an enterprise bean’s references to security roles aredeclared in the deployment descriptor. In this example, the deployment descriptor indicates thatthe enterprise beanAardvarkPayroll makes the security check usingisCallerInRole("payroll") in its businessmethod. The security role reference is scoped to the session or entity beanwhose declaration contains thesecurity-role-ref element. ...<enterprise-beans> ... <session> <ejb-name>AardvarkPayroll</ejb-name> <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class> ... <security-role-ref> <description> This security role should be assigned to the employees of the payroll department who are allowed to update employees’ salaries. </description> <role-name>payroll</role-name> </security-role-ref> ... </session> ...</enterprise-beans>... Defining a Security View of Enterprise BeansYou can define asecurity view of the enterprise beans contained in theejb-jarfile and pass this information along to the deployer. When a security viewis passed on to the deployer, the deployer uses this information to definemethod permissions for security roles. If you don’t define a security view, thedeployer will have to determine what each business method does to determine whichusers are authorized to call each method. A security view consists of a set ofsecurity roles, a semantic grouping ofpermissions that a given type of users of an application must have tosuccessfully access the application. Security roles are meant to be logical roles, representing atype of user. You can definemethod permissions for each security role. A methodpermission is a permission to invoke a specified group of methods of theenterprise beans’ business interface, home interface, component interface, and/or web service endpoints. Youcan specify an authentication mechanism that will be used to verify the identityof a user. It is important to keep in mind that security roles are usedto define the logical security view of an application. They should not beconfused with the user groups, users, principals, and other concepts that exist inthe Application Server. The following sections discuss setting up security roles, authentication mechanisms, and method permissionsthat define a security view: Defining Security RolesUse the@DeclareRoles and@RolesAllowed annotations to define security roles using Java language annotations.The set of security roles used by the application is the total ofthe security roles defined by the security role names used in the@DeclareRolesand@RolesAllowed annotations. You can augment the set of security roles defined for the application byannotations using thesecurity-role deployment descriptor element to define security roles, where youuse therole-name element to define the name of the security role. The following example illustrates how to define security roles in a deployment descriptor: ...<assembly-descriptor> <security-role> <description> This role includes the employees of the enterprise who are allowed to access the employee self-service application. This role is allowed only to access his/her own information. </description> <role-name>employee</role-name> </security-role> <security-role> <description> This role includes the employees of the human resources department. The role is allowed to view and update all employee records. </description> <role-name>hr-department</role-name> </security-role> <security-role> <description> This role includes the employees of the payroll department. The role is allowed to view and update the payroll entry for any employee. </description> <role-name>payroll-department</role-name> </security-role> <security-role> <description> This role should be assigned to the personnel authorized to perform administrative functions for the employee self-service application. This role does not have direct access to sensitive employee and payroll information. </description> <role-name>admin</role-name> </security-role> ...</assembly-descriptor> Linking Security Role References to Security RolesThe security role references used in the components of the application are linkedto the security roles defined for the application. In the absence of anyexplicit linking, a security role reference will be linked to a security rolehaving the same name. You can explicitly link all the security role references declared in the@DeclareRolesannotation orsecurity-role-ref elements for a component to the security roles defined bythe use of annotations (as discussed inDefining Security Roles) and/or in thesecurity-role elements. You use therole-link element to link each security role reference to a securityrole. The value of therole-link element must be the name of oneof the security roles defined in asecurity-role element, or by the@DeclareRoles or@RolesAllowed annotations (as discussed inDefining Security Roles). You do not needto use therole-link element to link security role references to security roleswhen therole-name used in the code is the same as the nameof thesecurity-role to which you would be linking. The following example illustrates how to link the security role reference namepayrollto the security role namedpayroll-department: ... <enterprise-beans> ... <session> <ejb-name>AardvarkPayroll</ejb-name> <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class> ... <security-role-ref> <description> This role should be assigned to the employees of the payroll department. Members of this role have access to anyone’s payroll record. The role has been linked to the payroll-department role. </description> <role-name>payroll</role-name> <role-link>payroll-department</role-link> </security-role-ref> ... </session> ... </enterprise-beans> ... Specifying an Authentication MechanismAuthentications mechanisms are specified in the runtime deployment descriptor. When annotations, such asthe@RolesAllowed annotation, are used to protect methods in the enterprise bean, youcan configure the Interoperable Object Reference (IOR) to enable authentication for an enterprise application.This is accomplished by adding the<login-config>element to the runtime deployment descriptor,sun-ejb-jar.xml. You can use theUSERNAME-PASSWORD authentication method for an enterprise bean. You canuse either theBASIC orCLIENT-CERT authentication methods for web service endpoints. For more information on specifying an authentication mechanism, readConfiguring IOR Security orExample: Securing an Enterprise Bean. Specifying Method PermissionsIf you have defined security roles for the enterprise beans in theejb-jar file, you can also specify the methods of the business interface, homeinterface, component interface, and/or web service endpoints that each security role is allowedto invoke. You can use annotations and/or the deployment descriptor for this purpose. Refer tothe following sections for more information on specifying method permissions: Specifying Method Permissions Using AnnotationsThe method permissions for the methods of a bean class can bespecified on the class, the business methods of the class, or both. Methodpermissions can be specified on a method of the bean class to overridethe method permissions value specified on the entire bean class. The following annotationsare used to specify method permissions:
The following example code illustrates the use of these annotations: @RolesAllowed("admin")public class SomeClass { public void aMethod () {...} public void bMethod () {...} ...}@Stateless public class MyBean implements A extends SomeClass { @RolesAllowed("HR") public void aMethod () {...} public void cMethod () {...} ...}In this example, assumingaMethod,bMethod, andcMethod are methods of business interfaceA, the method permissions values of methodsaMethod andbMethod are@RolesAllowed("HR") and@RolesAllowed("admin") respectively. The method permissions for methodcMethod have not been specified. To clarify, the annotations are not inherited by the subclass per se, theyapply to methods of the superclass which are inherited by the subclass. Also,annotations do not apply to CMP entity beans. An example that uses annotations to specify method permissions is described inExample: Securing an Enterprise Bean. Specifying Method Permissions Using Deployment DescriptorsNote -Any values explicitly specified in the deployment descriptor override any values specified inannotations. If a value for a method has not been specified in thedeployment descriptor, and a value has been specified for that method by meansof the use of annotations, the value specified in annotations will apply. Thegranularity of overriding is on the per-method basis. You define the method permissions in the deployment descriptor using themethod-permission elements,as discussed below:
Here is some other useful information about setting method permissions using deployment descriptors:
There are three legal styles for composing themethod element:
The following example illustrates how security roles are assigned method permissions in thedeployment descriptor: ... <method-permission> <role-name>employee</role-name> <method> <ejb-name>EmployeeService</ejb-name> <method-name>*</method-name> </method> </method-permission> <method-permission> <role-name>employee</role-name> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>findByPrimaryKey</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>getEmployeeInfo</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>updateEmployeeInfo</method-name> </method> </method-permission> <method-permission> <role-name>payroll-department</role-name> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>findByPrimaryKey</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>getEmployeeInfo</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>updateEmployeeInfo</method-name> </method> <method> <ejb-name>AardvarkPayroll</ejb-name> <method-name>updateSalary</method-name> </method> </method-permission> <method-permission> <role-name>admin</role-name> <method> <ejb-name>EmployeeServiceAdmin</ejb-name> <method-name>*</method-name> </method> </method-permission> ... Mapping Security Roles to Application Server GroupsThe Application Server assigns users toprincipals orgroups, rather than tosecurity roles. When you are developing a Java EE application, you don’t needto know what categories of users have been defined for the realm inwhich the application will be run. In the Java EE platform, the securityarchitecture provides a mechanism for mapping the roles defined in the application tothe users or groups defined in the runtime realm. To map a role name permitted by the application or module toprincipals (users) and groups defined on the server, use thesecurity-role-mapping element in theruntime deployment descriptor (sun-application.xml,sun-web.xml, orsun-ejb-jar.xml) file. The entry needs to declarea mapping between a security role used in the application and one ormore groups or principals defined for the applicable realm of the ApplicationServer. An example for thesun-application.xml file is shown below: <sun-application> <security-role-mapping> <role-name>CEO</role-name> <principal-name>jschwartz</principal-name> </security-role-mapping> <security-role-mapping> <role-name>ADMIN</role-name> <group-name>directors</group-name> </security-role-mapping></sun-application> The role name can be mapped to either a specific principal (user),a group, or both. The principal or group names referenced must be validprincipals or groups in the current default realm of the Application Server. Therole-name in this example must exactly match therole-name in thesecurity-role elementof the correspondingweb.xml file or the role name defined in the@DeclareRoles or@RolesAllowed annotations. Sometimes the role names used in the application are the same asthe group names defined on the Application Server. Under these circumstances, you can enablea default principal-to-role mapping on the Application Server using the Admin Console. Toenable the default principal-to-role-mapping, follow these steps:
For an enterprise application, you can specify the security role mapping at theapplication layer, insun-application.xml, or at the module layer, insun-ejb-jar.xml. When specified atthe application layer, the role mapping applies to all contained modules and overridessame-named role mappings at the module layer. The assembler is responsible for reconcilingthe module-specific role mappings to yield one effective mapping for the application. Both example applications demonstrate security role mapping. For more information, seeExample: Securing an Enterprise Bean andExample: Using theisCallerInRole andgetCallerPrincipal Methods. Propagating Security IdentityYou can specify whether a caller’s security identity should be used for theexecution of specified methods of an enterprise bean, or whether a specific run-asidentity should be used. Figure 29-2 illustrates this concept. Figure 29-2 Security Identity Propagation ![]() In this illustration, an application client is making a call to anenterprise bean method in one EJB container. This enterprise bean method, in turn,makes a call to an enterprise bean method in another container. The securityidentity during the first call is the identity of the caller. The securityidentity during the second call can be any of the following options:
Configuring a Component’s Propagated Security IdentityYou can configure an enterprise bean’s run-as, or propagated, security identity using eitherof the following:
Alternately, you can use theuse-caller-identity element to indicate that you want touse the identity of the original caller, as shown in the code below: <security-identity> <use-caller-identity /></security-identity> You must explicitly specify the run-as role name mapping to a given principalinsun-web.xml orsun-ejb-jar.xml if the given roles associate to more than oneuser principal. In either case, you will have to map the run-as role nameto a given principal defined on the Application Server if the given rolesassociate to more than one user principal. Mapping roles to principals is describedinMapping Security Roles to Application Server Groups. Trust between ContainersWhen an enterprise bean is designed so that either the original caller identityor a designated identity is used to call a target bean, thetarget bean will receive the propagated identity only; it will not receive anyauthentication data. There is no way for the target container to authenticate the propagated securityidentity. However, because the security identity is used in authorization checks (for example,method permissions or with theisCallerInRole() method), it is vitally important that thesecurity identity be authentic. Because there is no authentication data available to authenticatethe propagated identity, the target must trust that the calling container has propagatedan authenticated security identity. By default, the Application Server is configured to trust identities that are propagatedfrom different containers. Therefore, there are no special steps that you need totake to set up a trust relationship. Using Enterprise Bean Security AnnotationsAnnotations are used in code to relay information to the deployer about securityand other aspects of the application. Specifying this information in annotations or inthe deployment descriptor helps the deployer set up the appropriate security policy forthe enterprise bean application. Any values explicitly specified in the deployment descriptor override any values specified inannotations. If a value for a method has not been specified in thedeployment descriptor, and a value has been specified for that method by meansof the use of annotations, the value specified in annotations will apply. Thegranularity of overriding is on the per-method basis. The following is a listing of annotations that address security, can be usedin an enterprise bean, and are discussed in this tutorial:
Using Enterprise Bean Security Deployment Descriptor ElementsEnterprise JavaBeans components use an EJB deployment descriptor that must be namedMETA-INF/ejb-jar.xmland must be contained in the EJB JAR file. The role of thedeployment descriptor is to relay information to the deployer about security and otheraspects of the application. Specifying this information in annotations or in the deploymentdescriptor helps the deployer set up the appropriate security policy for the enterprisebean application. Note -Using annotations is the recommended method for adding security to enterprise bean applications. Any values explicitly specified in the deployment descriptor override any values specified inannotations. If a value for a method has not been specified in thedeployment descriptor, and a value has been specified for that method by meansof the use of annotations, the value specified in annotations will apply. Thegranularity of overriding is on the per-method basis. The following is a listing of deployment descriptor elements that address security, canbe used in an enterprise bean, and are discussed in this tutorial:
The schema forejb-jar deployment descriptors can be found in section 18.5,Deployment Descriptor XML Schema, intheEJB 3.0 Specification (JSR-220) athttp://jcp.org/en/jsr/detail?id=220. Configuring IOR SecurityThe EJB interoperability protocol is based on Internet Inter-ORB Protocol (IIOP/GIOP 1.2) andthe Common Secure Interoperability version 2 (CSIv2) CORBA Secure Interoperability specification. Enterprise beans that are deployed in one vendor’s server product are often accessedfrom Java EE client components that are deployed in another vendor’s product. CSIv2,a CORBA/IIOP-based standard interoperability protocol, addresses this situation by providing authentication, protection of integrityand confidentiality, and principal propagation for invocations on enterprise beans, where the invocationstake place over an enterprise’s intranet. CSIv2 configuration settings are specified in theInteroperable Object Reference (IOR) of the target enterprise bean. IOR configurations are defined inChapter 24 of the CORBA/IIOP specification,Secure Interoperability. This chapter can be downloadedfromhttp://www.omg.org/cgi-bin/doc?formal/02-06-60. The EJB interoperability protocol is defined in Chapter 14,Support for Distribution and Interoperability, of theEJB specification, which can be downloaded fromhttp://jcp.org/en/jsr/detail?id=220. Based on application requirements, IORs are configured in vendor-specific XML files, such assun-ejb-jar.xml, instead of in standard application deployment descriptor files, such asejb-jar.xml. For a Java EE application, IOR configurations are specified in Sun-specific xml files,for example,sun-ejb-jar_2_1-1.dtd. Theior-security-config element describes the security configuration information for theIOR. A description of some of the major subelements is provided below.
The following is an example that defines security for an IOR: <sun-ejb-jar> <enterprise-beans> <unique-id>1</unique-id> <ejb> <ejb-name>HelloWorld</ejb-name> <jndi-name>HelloWorld</jndi-name> <ior-security-config> <transport-config> <integrity>NONE</integrity> <confidentiality>NONE</confidentiality> <establish-trust-in-target> NONE </establish-trust-in-target> <establish-trust-in-client> NONE </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>NONE</caller-propagation> </sas-context> </ior-security-config> <webservice-endpoint> <port-component-name>HelloIF</port-component-name> <endpoint-address-uri> service/HelloWorld </endpoint-address-uri> <login-config> <auth-method>BASIC</auth-method> </login-config> </webservice-endpoint> </ejb> </enterprise-beans></sun-ejb-jar> Deploying Secure Enterprise BeansThe deployer is responsible for ensuring that an assembled application is secure afterit has been deployed in the target operational environment. If a security view(security annotations and/or a deployment descriptor) has been provided to the deployer, thesecurity view is mapped to the mechanisms and policies used by the securitydomain in the target operational environment, which in this case is the ApplicationServer. If no security view is provided, the deployer must set up theappropriate security policy for the enterprise bean application. Deployment information is specific to a web or application server. Accepting Unauthenticated UsersWeb applications accept unauthenticated web clients and allow these clients to make callsto the EJB container. The EJB specification requires a security credential for accessingEJB methods. Typically, the credential will be that of a generic unauthenticated user.The way you specify this credential is implementation-specific. In the Application Server, you must specify the name and password thatan unauthenticated user will use to log in by modifying the Application Serverusing the Admin Console:
Accessing Unprotected Enterprise BeansIf the deployer has granted full access to a method, any useror group can invoke the method. Conversely, the deployer can deny access toa method. To modify which role can be used in applications to grant authorization toanyone, specify a value for Anonymous Role. To set the Anonymous Rolefield, follow these steps:
Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |