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 Overview of Web Application Security Specifying Security Roles Using Annotations Specifying Security Roles Using Deployment Descriptor Elements Mapping Security Roles to Application Server Groups Checking Caller Identity Programmatically Declaring and Linking Role References Declaring Roles Using Annotations Declaring Roles Using Deployment Descriptor Elements Defining Security Requirements for Web Applications Declaring Security Requirements Using Annotations Using the@DeclareRoles Annotation Declaring Security Requirements in a Deployment Descriptor Specifying Security Constraints Specifying a Secure Connection Examples: Securing Web Applications Example: Using Form-Based Authentication with a JSP Page Creating a Web Client for Form-Based Authentication Creating the Login Form and the Error Page Specifying a Security Constraint Adding Authorized Roles and Users Mapping Application Roles to Application Server Groups Building, Packaging, and Deploying the Form-Based Authentication Example Using NetBeans IDE Building, Packaging, and Deploying the Form-Based Authentication Example Using Ant Testing the Form-Based Authentication Web Client Example: Basic Authentication with a Servlet Specifying the Security Constraint Adding Authorized Roles and Users Mapping Application Roles to Application Server Groups Building, Packaging, and Deploying the Servlet Basic Authentication Example Using NetBeans IDE Building, Packaging, and Deploying the Servlet Basic Authentication Example Using Ant Running the Basic Authentication Servlet Troubleshooting the Basic Authentication Example Example: Basic Authentication with JAX-WS Adding Security Elements to the Deployment Descriptor Building and Deployinghelloservice with Basic Authentication Using NetBeans IDE Building and Deployinghelloservice with Basic Authentication Using Ant Building and Running thehelloservice Client Application with Basic Authentication Using NetBeans IDE Building and Running thehelloservice Client Application with Basic Authentication Using Ant 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Defining Security Requirements for Web ApplicationsWeb applications are created by application developers who give, sell, or otherwise transferthe application to an application deployer for installation into a runtime environment. Applicationdevelopers communicate how the security is to be set up for the deployedapplicationdeclaratively by use of thedeployment descriptor mechanism orprogrammatically by use ofannotations. When this information is passed on to the deployer, the deployer usesthis information to define method permissions for security roles, set up user authentication,and whether or not to use HTTPS for transport. If you don’t definesecurity requirements, the deployer will have to determine the security requirements independently. If you specify a value in an annotation, and then explicitly specify thesame value in the deployment descriptor, the value in the deployment descriptor overridesany values specified in annotations. If a value for a servlet has notbeen specified in the deployment descriptor, and a value has been specified forthat servlet by means of the use of annotations, the value specifiedin annotations will apply. The granularity of overriding is on the per-servlet basis. The web application deployment descriptor may contain an attribute ofmetadata-complete ontheweb-app element. Themetadata-complete attribute defines whether the web application deployment descriptoris complete, or whether the class files of the JAR file should beexamined for annotations that specify deployment information. When themetadata-complete attribute is notspecified, or is set tofalse, the deployment descriptors examine the class files ofapplications for annotations that specify deployment information. When themetadata-complete attribute is settotrue, the deployment descriptor ignores any servlet annotations present in the class filesof the application. Thus, deployers can use deployment descriptors to customize or overridethe values specified in annotations. Many elements for security in a web application deployment descriptor cannot, as yet,be specified as annotations, therefore, for securing web applications, deployment descriptors are anecessity. However, where possible, annotations are the recommended method for securing web components. The following sections discuss the use of annotations and deployment descriptor elements tosecure web applications: Declaring Security Requirements Using AnnotationsTheJava Metadata Specification (JSR-175), which is part of J2SE 5.0 and greater, provides ameans of specifying configuration data in Java code. Metadata in Java code ismore commonly referred to in this document asannotations. In Java EE, annotationsare used to declare dependencies on external resources and configuration data in Java codewithout the need to define that data in a configuration file. Several commonannotations are specific to specifying security in any Java application. These common annotationsare specified in JSR-175,A Metadata Facility for the Java Programming Language, and JSR-250,Common Annotations for the Java Platform. Annotations specific to web components arespecified in theJava Servlet 2.5 Specification. In servlets, you can use the annotations discussed in the following sections tosecure a web application: Using the@DeclareRoles AnnotationThis annotation is used to define the security roles that comprise the securitymodel of the application. This annotation is specified on a class, and ittypically would be used to define roles that could be tested (forexample, by callingisUserInRole) from within the methods of the annotated class. Following is an example of how this annotation would be used. Inthis example,BusinessAdmin is the only security role specified, but the value of thisparameter can include a list of security roles specified by the application. @DeclareRoles("BusinessAdmin")public class CalculatorServlet { //...}Specifying@DeclareRoles("BusinessAdmin") is equivalent to defining the following inweb.xml: <web-app> <security-role> <role-name>BusinessAdmin</role-name> </security-role></web-app> The syntax for declaring more than one role is as shown inthe following example: @DeclareRoles({"Administrator", "Manager", "Employee"})This annotation is not used to link application roles to other roles. Whensuch linking is necessary, it is accomplished by defining an appropriatesecurity-role-refin the associated deployment descriptor, as described inDeclaring and Linking Role References. When a call is made toisUserInRole from the annotated class, the calleridentity associated with the invocation of the class is tested for membership inthe role with the same name as the argument toisUserInRole. Ifasecurity-role-ref has been defined for the argumentrole-name, the caller is tested formembership in the role mapped to therole-name. For further details on the@DeclareRoles annotation, refer to JSR–250,Common Annotations for the Java Platform, andUsing Enterprise Bean Security Annotations in thistutorial. Using the@RunAs AnnotationThe@RunAs annotation defines the role of the application during execution in aJava EE container. It can be specified on a class, allowing developers toexecute an application under a particular role. The role must map to theuser/group information in the container’s security realm. Thevalue element in the annotationis the name of a security role of the application during execution ina Java EE container. The use of the@RunAs annotation is discussed inmore detail inPropagating Security Identity. The following is an example that uses the@RunAs annotation: @RunAs("Admin")public class CalculatorServlet {@EJB private ShoppingCart myCart; public void doGet(HttpServletRequest, req, HttpServletResponse res) { //.... myCart.getTotal(); //.... }}//....}The@RunAs annotation is equivalent to therun-as element in the deploymentdescriptor. Declaring Security Requirements in a Deployment DescriptorWeb applications are created by application developers who give, sell, or otherwise transferthe application to an application deployer for installation into a runtime environment. Applicationdevelopers communicate how the security is to be set up for the deployedapplicationdeclaratively by use of thedeployment descriptor mechanism. A deployment descriptor enables an application’ssecurity structure, including roles, access control, and authentication requirements, to be expressed ina form external to the application. A web application is defined using a standard Java EEweb.xml deployment descriptor.A deployment descriptor is an XML schema document that conveys elements and configurationinformation for web applications. The deployment descriptor must indicate which version of theweb application schema (2.4 or 2.5) it is using, and the elements specifiedwithin the deployment descriptor must comply with the rules for processing that versionof the deployment descriptor. Version 2.5 of the Java Servlet Specification, which canbe downloaded atSRV.13, Deployment Descriptor, contains more information regarding the structure of deployment descriptors. The following code is an example of the elements in a deploymentdescriptor that apply specifically to declaring security for web applications or for resources withinweb applications. This example comes from section SRV.13.5.2,An Example of Security, from the JavaServlet Specification 2.5. <?xml version="1.0" encoding="ISO-8859-1"?><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <display-name>A Secure Application</display-name> <!-- SERVLET --> <servlet> <servlet-name>catalog</servlet-name> <servlet-class>com.mycorp.CatalogServlet</servlet-class> <init-param> <param-name>catalog</param-name> <param-value>Spring</param-value> </init-param> <security-role-ref> <role-name>MGR</role-name> <!-- role name used in code --> <role-link>manager</role-link> </security-role-ref> </servlet> <!-- SECURITY ROLE --> <security-role> <role-name>manager</role-name> </security-role> <servlet-mapping> <servlet-name>catalog</servlet-name> <url-pattern>/catalog/*</url-pattern> </servlet-mapping> <!-- SECURITY CONSTRAINT --> <security-constraint> <web-resource-collection> <web-resource-name>CartInfo</web-resource-name> <url-pattern>/catalog/cart/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>manager</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <!-- LOGIN CONFIGURATION--> <login-config> <auth-method>BASIC</auth-method> </login-config></web-app> As shown in the preceding example, the<web-app> element is the root elementfor web applications. The<web-app> element contains the following elements that are usedfor specifying security for a web application:
Some of the elements of web application security must be addressed in serverconfiguration files rather than in the deployment descriptor for the web application. Configuringsecurity on the Application Server is discussed in the following sections: The following sections provide more information on deployment descriptor security elements: Specifying Security ConstraintsSecurity constraints are a declarative way to define the protection of web content. Asecurity constraint is used to define access privileges to a collection of resourcesusing their URL mapping. Security constraints are defined in a deployment descriptor. Thefollowing example shows a typical security constraint, including all of the elements ofwhich it consists: <security-constraint> <display-name>ExampleSecurityConstraint</display-name> <web-resource-collection> <web-resource-name> ExampleWRCollection </web-resource-name> <url-pattern>/example</url-pattern> <http-method>POST</http-method> <http-method>GET</http-method> </web-resource-collection> <auth-constraint> <role-name>exampleRole</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint></security-constraint> As shown in the example, a security constraint (<security-constraint> in deployment descriptor)consists of the following elements:
Security constraints work only on the original request URI and not on callsmade throug aRequestDispatcher (which include<jsp:include> and<jsp:forward>). Inside the application, itis assumed that the application itself has complete access to all resources andwould not forward a user request unless it had decided that the requestinguser also had access. Many applications feature unprotected web content, which any caller can access without authentication.In the web tier, you provide unrestricted access simply by not configuring asecurity constraint for that particular request URI. It is common to have someunprotected resources and some protected resources. In this case, you will define securityconstraints and a login method, but they will not be used to controlaccess to the unprotected resources. Users won’t be asked to log in untilthe first time they enter a protected request URI. The Java Servlet specification defines the request URI as the part of aURLafter the host name and port. For example, let’s say you havean e-commerce site with a browsable catalog that you would want anyone tobe able to access, and a shopping cart area for customers only. Youcould set up the paths for your web application so that thepattern/cart/* is protected but nothing else is protected. Assuming that the applicationis installed at context path/myapp, the following are true:
A user will not be prompted to log in until the firsttime that user accesses a resource in thecart/ subdirectory. Specifying Separate Security Constraints for Different ResourcesYou can create a separate security constraint for different resources within your application.For example, you could allow users with the role ofPARTNER access tothePOST method of all resources with the URL pattern/acme/wholesale/*, and allow userswith the role ofCLIENT access to thePOST method of allresources with the URL pattern/acme/retail/*. An example of a deployment descriptorthat would demonstrate this functionality is the following: // SECURITY CONSTRAINT #1<security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>PARTNER</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint></security-constraint>// SECURITY CONSTRAINT #2<security-constraint> <web-resource-collection> <web-resource-name>retail</web-resource-name> <url-pattern>/acme/retail/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>CLIENT</role-name> </auth-constraint></security-constraint> When the sameurl-pattern andhttp-method occur in multiple security constraints, the constraintson the pattern and method are defined by combining the individual constraints, whichcould result in unintentional denial of access. Section 12.7.2 of theJava Servlet 2.5 Specification (downloadablefromhttp://jcp.org/en/jsr/detail?id=154) gives an example that illustrates the combination of constraints and howthe declarations will be interpreted. Specifying a Secure ConnectionA user data constraint (<user-data-constraint> in the deployment descriptor) requires that all constrainedURL patterns and HTTP methods specified in the security constraint are received overa protected transport layer connection such as HTTPS (HTTP over SSL). A userdata constraint specifies a transport guarantee (<transport-guarantee> in the deployment descriptor). The choices fortransport guarantee includeCONFIDENTIAL,INTEGRAL, orNONE. If you specifyCONFIDENTIAL orINTEGRALas a security constraint, that type of security constraint applies to all requests thatmatch the URL patterns in the web resource collection and not justto the login dialog box. The following security constraint includes a transport guarantee: <security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>PARTNER</role-name> </auth-constraint><user-data-constraint><transport-guarantee>CONFIDENTIAL</transport-guarantee></user-data-constraint></security-constraint> The strength of the required protection is defined by the value ofthe transport guarantee. SpecifyCONFIDENTIAL when the application requires that data be transmitted soas to prevent other entities from observing the contents of the transmission. SpecifyINTEGRAL when the application requires that the data be sent between client andserver in such a way that it cannot be changed in transit. SpecifyNONE to indicate that the container must accept the constrained requests on anyconnection, including an unprotected one. The user data constraint is handy to use in conjunction with basicand form-based user authentication. When the login authentication method is set toBASIC orFORM, passwords are not protected, meaning that passwords sent between a client anda server on an unprotected session can be viewed and intercepted by thirdparties. Using a user data constraint with the user authentication mechanism can alleviate thisconcern. Configuring a user authentication mechanism is described inSpecifying an Authentication Mechanism. To guarantee that data is transported over a secure connection, ensure that SSLsupport is configured for your server. If your server is the ApplicationServer, SSL support is already configured. If you are using another server, consult thedocumentation for that server for information on setting up SSL support. Note -Good Security Practice: If you are using sessions, after you switch to SSLyou should never accept any further requests for that session that are non-SSL.For example, a shopping site might not use SSL until the checkout page,and then it might switch to using SSL to accept your cardnumber. After switching to SSL, you should stop listening to non-SSL requests forthis session. The reason for this practice is that the session ID itselfwas not encrypted on the earlier communications. This is not so bad whenyou’re only doing your shopping, but after the credit card information is storedin the session, you don’t want a bad guy trying to fake thepurchase transaction against your credit card. This practice could be easily implemented usinga filter. Specifying an Authentication MechanismTo specify an authentication mechanism for your web application, declare alogin-config elementin the application deployment descriptor. Thelogin-config element is used to configure theauthentication method and realm name that should be used for this application, andthe attributes that are needed by the form login mechanism when form-based loginis selected. The sub-elementauth-method configures the authentication mechanism for the web application. Theelement content must be either BASIC, DIGEST, FORM, CLIENT-CERT, or a vendor-specific authenticationscheme. Therealm-name element indicates the realm name to use for theauthentication scheme chosen for the web application. Theform-login-config element specifies the login anderror pages that should be used when FORM based login is specified. The authentication mechanism you choose specifies how the user is prompted to login.If the<login-config> element is present, and the<auth-method> element contains a valueother thanNONE, the user must be authenticated before it can access any resourcethat is constrained by the use of asecurity-constraint element in thesame deployment descriptor (readSpecifying Security Constraints for more information on security constraints). If youdo not specify an authentication mechanism, the user will not be authenticated. When you try to access a web resource that is constrained byasecurity-constraint element, the web container activates the authentication mechanism that has beenconfigured for that resource. To specify an authentication method, place the<auth-method> elementbetween<login-config> elements in the deployment descriptor, like this: <login-config> <auth-method>BASIC</auth-method></login-config> An example of a deployment descriptor that constrains all web resources for thisapplication (initalics below) and requires HTTP basic authentication when you try toaccess that resource (inbold below) is shown here: <?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>basicauth</display-name> <servlet> <display-name>index</display-name> <servlet-name>index</servlet-name> <jsp-file>/index.jsp</jsp-file> </servlet> <security-role> <role-name>loginUser</role-name> </security-role><security-constraint><display-name>SecurityConstraint1</display-name><web-resource-collection><web-resource-name>WRCollection</web-resource-name><url-pattern>/*</url-pattern></web-resource-collection><auth-constraint><role-name>loginUser</role-name></auth-constraint></security-constraint><login-config><auth-method>BASIC</auth-method></login-config></web-app> Before you can authenticate a user, you must have a database ofuser names, passwords, and roles configured on your web or application server. The authentication mechanisms are discussed further in the following sections: HTTP Basic AuthenticationHTTP Basic Authentication requires that the server request a user name and password from theweb client and verify that the user name and password are valid bycomparing them against a database of authorized users. When basic authentication is declared,the following actions occur:
Figure 30-2 shows what happens when you specify HTTP basic authentication. Figure 30-2 HTTP Basic Authentication ![]() The following example shows how to specify basic authentication in your deployment descriptor: <login-config> <auth-method>BASIC</auth-method></login-config> HTTP basic authentication is not a secure authentication mechanism. Basic authentication sends usernames and passwords over the Internet as text that is Base64 encoded, andthe target server is not authenticated. This form of authentication can expose usernames and passwords. If someone can intercept the transmission, the user name andpassword information can easily be decoded. However, when a secure transport mechanism, suchas SSL, or security at the network level, such as the IPSEC protocolor VPN strategies, is used in conjunction with basic authentication, some of theseconcerns can be alleviated. Example: Basic Authentication with JAX-WS is an example application that uses HTTP basic authentication in a JAX-WSservice.Example: Using Form-Based Authentication with a JSP Page can be easily modified to demonstrate basic authentication. To do so,replace the text between the<login-config> elements with those shown in this section. Form-Based AuthenticationForm-based authentication allows the developer to control the look and feel of thelogin authentication screens by customizing the login screen and error pages that anHTTP browser presents to the end user. When form-based authentication is declared, thefollowing actions occur:
Figure 30-3 shows what happens when you specify form-based authentication. Figure 30-3 Form-Based Authentication ![]() The following example shows how to declare form-based authentication in your deployment descriptor: <login-config> <auth-method>FORM</auth-method> <realm-name>file</realm-name> <form-login-config> <form-login-page>/logon.jsp</form-login-page> <form-error-page>/logonError.jsp</form-error-page> </form-login-config></login-config> The login and error page locations are specified relative to the location ofthe deployment descriptor. Examples of login and error pages are shown inCreating the Login Form and the Error Page. Form-based authentication is not particularly secure. In form-based authentication, the content of theuser dialog box is sent as plain text, and the target server isnot authenticated. This form of authentication can expose your user names and passwordsunless all connections are over SSL. If someone can intercept the transmission, theuser name and password information can easily be decoded. However, when a securetransport mechanism, such as SSL, or security at the network level, such asthe IPSEC protocol or VPN strategies, is used in conjunction with form-based authentication,some of these concerns can be alleviated. The sectionExample: Using Form-Based Authentication with a JSP Page is an example application that uses form-based authentication. Using Login FormsWhen creating a form-based login, be sure to maintain sessions using cookies orSSL session information. As shown inForm-Based Authentication, for authentication to proceed appropriately, the action of thelogin form must always bej_security_check. This restriction is made so that the loginform will work no matter which resource it is for, and to avoidrequiring the server to specify the action field of the outbound form. Thefollowing code snippet shows how the form should be coded into theHTML page: <form method="POST" action="j_security_check"><input type="text" name="j_username"><input type="password" name="j_password"></form> HTTPS Client AuthenticationHTTPS Client Authentication requires the client to possess a Public Key Certificate (PKC).If you specifyclient authentication, the web server will authenticate the client using theclient’s public key certificate. HTTPS Client Authentication is a more secure method of authentication than either basicor form-based authentication. It uses HTTP over SSL (HTTPS), in which the serverauthenticates the client using the client’s Public Key Certificate (PKC). Secure Sockets Layer (SSL)technology provides data encryption, server authentication, message integrity, and optional client authentication fora TCP/IP connection. You can think of a public key certificate as thedigital equivalent of a passport. It is issued by a trusted organization, whichis called a certificate authority (CA), and provides identification for the bearer. Before using HTTP Client Authentication, you must make sure that the following actionshave been completed:
The following example shows how to declare HTTPS client authentication in your deploymentdescriptor: <login-config> <auth-method>CLIENT-CERT</auth-method></login-config> Mutual AuthenticationWithmutual authentication, the server and the client authenticate one another. There are twotypes of mutual authentication:
When using certificate-based mutual authentication, the following actions occur:
Figure 30-4 shows what occurs during certificate-based mutual authentication. Figure 30-4 Certificate-Based Mutual Authentication ![]() In user name- and password-based mutual authentication, the following actions occur:
Figure 30-5 shows what occurs during user name- and password-based mutual authentication. Figure 30-5 User Name- and Password-Based Mutual Authentication ![]() Digest AuthenticationLike HTTP basic authentication,HTTP Digest Authentication authenticates a user based on a user nameand a password. However, the authentication is performed by transmitting the password inan encrypted form which is much more secure than the simple Base64 encodingused by basic authentication. Digest authentication is not currently in widespread use, andis not implemented in the Application Server, therefore, there is no further discussionof it in this document. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |