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

30.  Securing Web Applications

Overview of Web Application Security

Working with Security Roles

Declaring Security Roles

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

Using the@RunAs Annotation

Declaring Security Requirements in a Deployment Descriptor

Specifying Security Constraints

Specifying a Secure Connection

Specifying an Authentication Mechanism

HTTP Basic Authentication

Form-Based Authentication

HTTPS Client Authentication

Digest Authentication

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

Declaring Security Roles

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

Annotating the Service

Adding Security Elements to the Deployment Descriptor

Linking Roles to Groups

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

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

Examples: Securing Web Applications

There are several ways in which you can secure web applications. These includethe following options:

  • You can define a user authentication method for an application in its deployment descriptor. Authentication verifies the identity of a user, device, or other entity in a computer system, usually as a prerequisite to allowing access to resources in a system. When a user authentication method is specified for an application, the web container activates the specified authentication mechanism when you attempt to access a protected resource.

    The options for user authentication methods are discussed inSpecifying an Authentication Mechanism. All of the example security applications use a user authentication method.

  • You can define a transport guarantee for an application in its deployment descriptor. Use this method to run over an SSL-protected session and ensure that all message content is protected for confidentiality or integrity. The options for transport guarantees are discussed inSpecifying a Secure Connection.

    When running over an SSL-protected session, the server and client can authenticate one another and negotiate an encryption algorithm and cryptographic keys before the application protocol transmits or receives its first byte of data.

    SSL technology allows web browsers and web servers to communicate over a secure connection. In this secure connection, the data is encrypted before being sent, and then is decrypted upon receipt and before processing. Both the browser and the server encrypt all traffic before sending any data. For more information, seeEstablishing a Secure Connection Using SSL.

    Digital certificates are necessary when running HTTP over SSL (HTTPS). The HTTPS service of most web servers will not run unless a digital certificate has been installed. Digital certificates have already been created for the Application Server.

The following examples use annotations, programmatic security, and/or declarative security to demonstrate addingsecurity to existing web applications:

The following examples demonstrate adding basic authentication to an EJB endpoint or enterprisebean:

Example: Using Form-Based Authentication with a JSP Page

This example discusses how to use form-based authentication with a basic JSP page.With form-based authentication, you can customize the login screen and error pages thatare presented to the web client for authentication of their user name andpassword. When a user submits their name and password, the server determines ifthe user name and password are those of an authorized user and, ifauthorized, sends the requested web resource. If the topic of authentication is newto you, please refer to the sectionSpecifying an Authentication Mechanism.

In general, the following steps are necessary for adding form-based authentication to anunsecured JSP page, such as the one described inWeb Modules. In theexample application included with this tutorial, many of these steps have been completedfor you and are listed here simply to show what needs to bedone should you wish to create a similar application. The completed version ofthis example application can be found in the directorytut-install/javaeetutorial5/examples/web/hello1_formauth/.

The following steps describe how to set up your system for runningthe example applications, describe the sample application, and provide the steps for compiling, packaging,deploying, and testing the example application.

  1. If you have not already done so, set up your system so that the Ant tool and/or NetBeans IDE will run properly. To do this, follow the instructions inBuilding the Examples.

  2. If you have not already done so, add an authorized user to the Application Server. For this example, add users to thefile realm of the Application Server and assign the user to the groupuser. This topic is discussed more inAdding Authorized Roles and Users.

  3. Create a web module as described inWeb Modules. The subsequent steps discuss adding security to this basic application. The resulting application is found in the directorytut-install/javaeetutorial5/examples/web/hello1_formauth/.

  4. Create the login form and login error form pages. Files for the example application can be viewed attut-install/javaeetutorial5/examples/web/hello1_formauth/web. These pages are discussed inCreating the Login Form and the Error Page.

  5. Create aweb.xml deployment descriptor and add the appropriate security elements (the application on which this section is based did not originally require a deployment descriptor.) The deployment descriptor for the example application can be viewed attut-install/javaeetutorial5/examples/hello1_formauth/web/WEB-INF. The security elements for theweb.xml deployment descriptor are described inSpecifying a Security Constraint.

  6. Map the role name defined for this resource (loginUser) to a group of users defined on the Application Server. For more information on how to do this, readMapping Application Roles to Application Server Groups.

  7. Build, package, deploy, and run the web application by following the steps inBuilding, Packaging, and Deploying the Form-Based Authentication Example Using NetBeans IDE orBuilding, Packaging, and Deploying the Form-Based Authentication Example Using Ant.

  8. Test the web client, following the steps inTesting the Form-Based Authentication Web Client.

Creating a Web Client for Form-Based Authentication

The web client in this example is a standard JSP page, andannotations are not used in JSP pages because JSP pages are compiled asthey are presented to the browser. Therefore, none of the code that addsform-based authentication to the example is included in the web client. The codefor the JSP page used in this example,hello1_formauth/web/index.jsp, is exactly the same asthe code used for the unsecured JSP page from the example application attut-install/javaeetutorial5/examples/web/hello1/web/index.jsp.

The information that adds form-based authentication to this example is specified in thedeployment descriptor. This information is discussed inSpecifying a Security Constraint.

Creating the Login Form and the Error Page

When using form-based login mechanisms, you must specify a page that contains theform you want to use to obtain the user name and password,as well as which page to display if login authentication fails. This section discussesthe login form and the error page used in this example. ThesectionSpecifying a Security Constraint shows how you specify these pages in the deployment descriptor.

The login page can be an HTML page, a JSP page, ora servlet, and it must return an HTML page containing a form thatconforms to specific naming conventions (see the Java Servlet 2.5 specification for moreinformation on these requirements). To do this, include the elements that accept username and password information between<form></form> tags in your login page. The content ofan HTML page, JSP page, or servlet for a login page should becoded as follows:

<form method=post action="j_security_check" >    <input type="text"  name= "j_username" >    <input type="password"  name= "j_password" ></form>

The full code for the login page used in this example canbe found attut-install/javaeetutorial5/examples/web/hello1_formauth/web/logon.jsp. An example of the running login form pageis shown later inFigure 30-6. Here is the code for this page:

<html><head>    <title>Login Page</title></head><h2>Hello, please log in:</h2><br><br><form action="j_security_check" method=post>    <p><strong>Please Enter Your User Name: </strong><input type="text" name="j_username" size="25">    <p><p><strong>Please Enter Your Password: </strong><input type="password" size="15" name="j_password">    <p><p>    <input type="submit" value="Submit">    <input type="reset" value="Reset"></form></html>

The login error page is displayed if the user enters a username and password combination that is not authorized to access the protected URI.For this example, the login error page can be found attut-install/javaeetutorial5/examples/web/hello1_formauth/web/logonError.jsp. Forthis example, the login error page explains the reason for receiving the errorpage and provides a link that will allow the user to try again.Here is the code for this page:

<html><head>    <title>Login Error</title></head><body>    <c:url var="url" value="/index.jsp"/>    <h2>Invalid user name or password.</h2>    <p>Please enter a user name or password that is authorized to access this     application. For this application, this means a user that has been created in the     <code>file</code> realm and has been assigned to the <em>group</em> of     <code>user</code>.  Click here to <a href="${url}">Try Again</a></p></body></html>
Specifying a Security Constraint

This example takes a very simple JSP page-based web application and adds form-basedsecurity to this application. The JSP page is exactly the same as theJSP page used in the example described inWeb Modules. All security forthis example is declared in the deployment descriptor for the application. A securityconstraint is defined in the deployment descriptor that tells the server to senda login form to collect user data, verify that the user is authorizedto access the application, and, if so, display the JSP page to theuser.

If this client were a web service endpoint and not a JSPpage, you could use annotations to declare security roles and to specify whichroles were allowed access to which methods. However, there is no resource injectionin JSP pages, so you cannot use annotations and must use the equivalentdeployment descriptor elements.

Deployment descriptor elements are described inDeclaring Security Requirements in a Deployment Descriptor.

The following sample code shows the deployment descriptor used in this example ofform-based login authentication, which can be found intut-install/javaeetutorial5/examples/web/hello1_formauth/web/WEB-INF/web.xml.

<!-- FORM-BASED LOGIN AUTHENTICATION EXAMPLE --><?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <display-name>hello1_formauth</display-name>       <servlet>             <display-name>index</display-name>            <servlet-name>index</servlet-name>            <jsp-file>/index.jsp</jsp-file>      </servlet>     <security-constraint>             <display-name>SecurityConstraint</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>            <user-data-constraint>                <transport-guarantee>NONE</transport-guarantee>            </user-data-constraint>       </security-constraint>      <login-config><auth-method>FORM</auth-method>         <form-login-config><form-login-page>/logon.jsp</form-login-page><form-error-page>/logonError.jsp</form-error-page>          </form-login-config>     </login-config>     <security-role>        <role-name>loginUser</role-name>    </security-role></web-app>

More description of the elements that declare security in a deployment descriptor canbe found inSpecifying Security Constraints.

Protecting Passwords with SSL

Passwords are not protected for confidentiality with HTTP basic or form-based authentication, meaning thatpasswords sent between a client and a server on an unprotected session canbe viewed and intercepted by third parties. To overcome this limitation, you canrun these authentication protocols over an SSL-protected session and ensure that all messagecontent is protected for confidentiality.

A<transport-guarantee> element indicates whether or not the protected resources should travel overprotected transport. For simplicity, this example does not require protected transport, but ina real world application, you would want to set this value toCONFIDENTIALto ensure that the user name and password are not observed during transmission. Whenrunning on protected transport, you can run the application over the secure SSLprotocol,https, and specify the secure port where your SSL connector is created(the default for the Application Server is8181). If you do notspecify the HTTPS protocol, the server will automatically redirect the application to thesecure port.

Adding Authorized Roles and Users

To authenticate a user and allow that user access to protected resources onthe Application Server, you must link the roles defined in the applicationto the users defined for the Application Server.

  • An application may definesecurity roles, which are a logical grouping of users, classified by common traits such as customer profile or job title.

  • The Application Server has multiplerealms, each of which generally includes a database of authorized users, their passwords, and one or more logical groups to which the each user belongs.

When an application is deployed, the application-specific security roles are mapped to securityidentities in the runtime environment, such asprincipals (identities assigned to usersas a result of authentication) orgroups. Based on this mapping, auser who has been assigned a certain security role has associated access rightsto a web application deployed onto a server.

As shown in the deployment descriptor for this example application, the security constraintspecifies that users assigned to the role ofloginUser are authorized toaccess any of the files in thehello1_formauth application. In this example,when a resource that is constrained by this same security constraint is accessed,for example,hello1_formauth/web/index.jsp, the Application Server sends the login form, receives thelogin information, and checks to see if the user is in a groupthat has been mapped to the role ofloginUser. If the user nameand password are those of an authorized user, access to the resource isgranted to the requester.

To set up users for this example application, follow these steps:

  1. Using the Admin Console, create a user in thefile realm of the Application Server and assign that user to the groupuser. Make sure to note the user name and password that you enter in this step so that you can use it for testing the application later (these fields are case-sensitive). If you need help with the steps required to accomplish this task, readManaging Users and Groups on the Application Server for more information.

  2. Map the application security role ofloginUser to thegroup ofuser that has been configured on the Application Server. For more information on how to do this mapping, readMapping Application Roles to Application Server Groups.

Mapping Application Roles to Application Server Groups

Map the role ofloginUser defined in the application to the groupofuser defined on the Application Server by adding asecurity-role-mapping element to thesun-web.xml runtime deployment descriptor file. To deploy a WAR on the Application Server,the WAR file must contain a runtime deployment descriptor. The runtime deployment descriptoris an XML file that contains information such as the context root ofthe web application and the mapping of the portable names of an application’sresources to the Application Server’s resources.

The runtime deployment descriptor for this example,tut-install/javaeetutorial5/examples/web/hello1_formauth/web/WEB-INF/sun-web.xml, looks like this:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd"><sun-web-app>    <context-root>/hello1_formauth</context-root><security-role-mapping><role-name>loginUser</role-name><group-name>user</group-name></security-role-mapping></sun-web-app>
Building, Packaging, and Deploying the Form-Based Authentication Example Using NetBeans IDE

To build, package, and deploy this application using NetBeans IDE, follow these steps:

  1. Follow the instructions inBuilding the Examples if you have not already done so. This step is necessary to provide the Ant targets with the location of your tutorial and Application Server installations.

  2. Add users to thefile realm of the Application Server as described inAdding Authorized Roles and Users if you have not already done so.

  3. Open the project in NetBeans IDE by selecting File→Open Project.

  4. Browse to thetut-install/javaeetutorial5/examples/web/hello1_formauth/ directory.

  5. Make sure that Open as Main Project is selected.

  6. Select Open Project.

  7. If you are prompted to regenerate thebuild-impl.xml file, select the Regenerate button.

  8. Right-clickhello1_formauth in the Projects pane, then select Clean and Build.

  9. Right-clickhello1_formauth in the Projects pane, then select Undeploy and Deploy.

  10. Follow the steps inTesting the Form-Based Authentication Web Client.

Building, Packaging, and Deploying the Form-Based Authentication Example Using Ant

To build, package, and deploy this application using the Ant tool, follow thesesteps:

  1. Follow the instructions inBuilding the Examples if you have not already done so. This step is necessary to provide the Ant targets with the location of your tutorial and Application Server installations.

  2. Add users to thefile realm of the Application Server as described inAdding Authorized Roles and Users if you have not already done so.

  3. From a terminal window or command prompt, change to thetut-install/javaeetutorial5/examples/web/hello1_formauth/ directory.

  4. Enter the following command at the terminal window or command prompt:

    ant

    This target will spawn any necessary compilations, copy files to thetut-install/javaeetutorial5/examples/web/hello1_formauth/build/ directory, create the WAR file, and copy it to thetut-installjavaeetutorial5/examples/web/hello1_formauth/dist/ directory.

  5. Deploy the WAR namedhello1_formauth.war onto the Application Server using Ant by entering the following command at the terminal window or command prompt:

    ant deploy
  6. Follow the steps inTesting the Form-Based Authentication Web Client.

Testing the Form-Based Authentication Web Client

To run the web client, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in your web browser:

    http://localhost:8080/hello1_formauth

    Note -If you set the transport guarantee toCONFIDENTIAL as discussed inProtecting Passwords with SSL, you must load the application in a web browser usinghttps for the protocol, the HTTPS port that you specified during installation for the port (by default this port is 8181), and the context name for the application you wish to run. For the form-based authentication example, you could run the example using the following URL:https://localhost:8181/hello1_formauth.


    The login form displays in the browser, as shown inFigure 30-6.

  3. Enter a user name and password combination that corresponds to a user that has already been created in thefile realm of the Application Server and has been assigned to the group ofuser, as discussed inAdding Authorized Roles and Users.

  4. Click the Submit button. Form-based authentication is case-sensitive for both the user name and password, so enter the user name and password exactly as defined for the Application Server.

    If you enteredMy_Name as the name andMy_Pwd for the password, the server returns the requested resource if all of the following conditions are met:

    • There is a user defined for the Application Server with the user name ofMy_Name.

    • The user with the user name ofMy_Name has a password ofMy_Pwd defined for the Application Server.

    • The userMy_Name with the passwordMy_Pwd is assigned to the group ofuser on the Application Server.

    • The role ofloginUser, as defined for the application, is mapped to the group ofuser, as defined for the Application Server.

      When these conditions are met, and the server has authenticated the user, the application will display as shown inFigure 30-7.

  5. Enter your name and click the Submit button. Because you have already been authorized, the name you enter in this step does not have any limitations. You have unlimited access to the application now.

    The application responds by saying “Hello” to you, as shown inFigure 30-8.

Figure 30-6 Form-Based Login Page

Screen shot of form-based login page showing text fields for user name and password

Figure 30-7 Running Web Application

Screen shot of running form-based web application with text field for user to type name

Figure 30-8 The Running Form-Based Authentication Example

Screen shot of running form-based web application showing response

Note -For repetitive testing of this example, you may need to close and reopenyour browser. You should also run theant clean andant undeploy commandsto ensure a fresh build if using the Ant tool, or select Cleanand Build then Undeploy and Deploy if using NetBeans IDE.


Example: Basic Authentication with a Servlet

This example discusses how to use basic authentication with a servlet. With basicauthentication of a servlet, the web browser presents a standard login dialog thatis not customizable. When a user submits their name and password, the serverdetermines if the user name and password are those of an authorized userand sends the requested web resource if the user is authorized to viewit. If the topic of authentication is new to you, please referto the sectionSpecifying an Authentication Mechanism.

In general, the following steps are necessary for adding basic authentication to anunsecured servlet, such as the one described inWeb Modules. In the exampleapplication included with this tutorial, many of these steps have been completed foryou and are listed here simply to show what needs to be doneshould you wish to create a similar application. The completed version of thisexample application can be found in the directorytut-install/javaeetutorial5/examples/web/hello2_basicauth/.

The following steps describe how to set up your system for runningthe example applications, describe the sample application, and provide the steps for compiling, packaging,deploying, and testing the example application.

  1. If you have not already done so, set up your system so that the Ant tool and/or NetBeans IDE will run properly. To do this, follow the instructions inBuilding the Examples.

  2. If you have not already done so, add an authorized user to the Application Server. For this example, add users to thefile realm of the Application Server and assign the user to the groupuser. This topic is discussed more inAdding Authorized Roles and Users.

  3. Create a web module as described inWeb Modules for the servlet example,hello2. The subsequent steps discuss adding security to this basic application. The files for this example application are intut-install/javaeetutorial5/examples/web/hello2_basicauth/.

  4. Declare the roles that will be used in this application. For this example, this is done by adding the@DeclareRoles annotation toGreetingServlet.java. This code is shown inDeclaring Security Roles.

  5. Add the appropriate security elements to theweb.xml deployment descriptor. The deployment descriptor for the example application can be viewed attut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/web.xml. The security elements are described inSpecifying the Security Constraint.

  6. Map the role name defined for this resource (helloUser) to a group of users defined on the Application Server. For more information on how to do this, readMapping Application Roles to Application Server Groups.

  7. Build, package, and deploy the web application by following the steps inBuilding, Packaging, and Deploying the Servlet Basic Authentication Example Using NetBeans IDE orBuilding, Packaging, and Deploying the Servlet Basic Authentication Example Using Ant.

  8. Run the web application by following the steps described inRunning the Basic Authentication Servlet.

  9. If you have any problems running this example, refer to the troubleshooting tips inTroubleshooting the Basic Authentication Example.

Declaring Security Roles

There are two annotations that can be used with servlets:@DeclareRoles and@RunAs. In this example, the@DeclareRoles annotation is used to specify whichroles are referenced in this example.

The following section of thetut-install/javaeetutorial5/examples/web/hello2_basicauth/src/servlets/GreetingServlet.java file contains the code necessary todeclare that the role ofhelloUser is used in this application:

package servlets;import java.io.*;import java.util.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;import javax.annotation.security.DeclareRoles;/*** This is a simple example of an HTTP Servlet that can only be accessed* by an authenticated user.  It responds to the GET* method of the HTTP protocol.*/@DeclareRoles("helloUser")public class GreetingServlet extends HttpServlet {    public void doGet (HttpServletRequest request,        HttpServletResponse response)            throws ServletException, IOException

You could also declare security roles using the<security-role> element in thedeployment descriptor. If you prefer to declare security roles this way, readDeclaring Roles Using Deployment Descriptor Elements.

Specifying the Security Constraint

This example takes a very simple servlet-based web application and adds basic authenticationto this application. The servlet is basically the same as the servlet usedin the example described inWeb Modules, with the exception of the annotationsadded and discussed inDeclaring Security Roles.

The security constraint for this example is declared in the application deployment descriptor.The security constraint tells the server or browser to perform the following tasks:

  • Send a standard login dialog to collect user name and password data

  • Verify that the user is authorized to access the application

  • If authorized, display the servlet to the user

Deployment descriptors elements are described inDeclaring Security Requirements in a Deployment Descriptor.

The following sample code shows the security elements for the deployment descriptor usedin this example of basic authentication, which can be found intut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/web.xml.

    <security-constraint>        <display-name>SecurityConstraint</display-name>        <web-resource-collection>             <web-resource-name>WRCollection</web-resource-name>            <url-pattern>/greeting</url-pattern>        </web-resource-collection>        <auth-constraint>            <role-name>helloUser</role-name>        </auth-constraint>        <user-data-constraint>             <transport-guarantee>NONE</transport-guarantee>        </user-data-constraint>    </security-constraint>    <login-config>        <auth-method>BASIC</auth-method>        <realm-name>file</realm-name>    </login-config>

More description of the elements that declare security in a deployment descriptor canbe found inSpecifying Security Constraints.

Protecting Passwords with SSL

Passwords are not protected for confidentiality with HTTP basic or form-based authentication, meaning thatpasswords sent between a client and a server on an unprotected session canbe viewed and intercepted by third parties. To overcome this limitation, you canrun these authentication protocols over an SSL-protected session and ensure that all messagecontent is protected for confidentiality.

A<transport-guarantee> element indicates whether or not the protected resources should travel overprotected transport. For simplicity, this example does not require protected transport, but ina real world application, you would want to set this value toCONFIDENTIALto ensure that the user name and password are not observed during transmission. Whenrunning on protected transport, you need to use the secure SSL protocol,https, and specify the secure port where your SSL connector is created (thedefault for the Application Server is8181).

Adding Authorized Roles and Users

To authenticate a user and allow that user access to protected resources onthe Application Server, you must link the roles defined in the applicationto the users defined for the Application Server.

  • Asecurity role, which is defined at the application level, is a logical grouping of users, classified by common traits such as customer profile or job title.

  • The Application Server has multiplerealms, each of which generally includes a database of authorized users, their passwords, and one or more logical groups to which the each user belongs.

When an application is deployed, the application-specific security roles are mapped to securityidentities in the runtime environment, such asprincipals (identities assigned to usersas a result of authentication) orgroups. Based on this mapping, auser who has been assigned a certain security role has associated access rightsto a web application deployed onto a server.

As shown in the deployment descriptor for this example application, the security constraintspecifies that users assigned to the role ofhelloUser are authorized toaccess the URL pattern/greeting. In this example, when this resource (because itis constrained by a security constraint) is accessed, the Application Server sends adefault login dialog, receives the login information, and checks to see if theuser is in a group that has been mapped to the role ofhelloUser. If the user name and password are those of an authorized user,access to the resource is granted to the requester.

To set up users for this example application, follow these steps:

  1. If you have not already done so, create a user in thefile realm of the Application Server and assign that user to the groupuser. Make sure to note the user name and password that you enter in this step so that you can use it for testing the application later. If you need help with the steps required to accomplish this task, readManaging Users and Groups on the Application Server for more information.

  2. Map the application security role ofhelloUser to thegroup ofuser that has been configured on the Application Server. For more information on how to do this mapping, readMapping Application Roles to Application Server Groups.

Mapping Application Roles to Application Server Groups

Map the role ofhelloUser defined in the application to the group ofuser defined on the Application Server by adding asecurity-role-mapping element to thesun-web.xml runtime deployment descriptor file. The runtime deployment descriptor is an XML file thatcontains information such as the context root of the web application and themapping of the portable names of an application’s resources to the Application Server’sresources.

The runtime deployment descriptor for this example,tut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/sun-web.xml, looks like this:

<sun-web-app>    <context-root>/hello2_basicauth</context-root>    <security-role-mapping>        <role-name>helloUser</role-name>        <group-name>user</group-name>    </security-role-mapping></sun-web-app>
Building, Packaging, and Deploying the Servlet Basic Authentication Example Using NetBeans IDE

To build, package, and deploy theweb/hello2_basicauth example application using NetBeans IDE, followthese steps:

  1. If you have not already done so, follow the instructions inBuilding the Examples.

  2. If you have not already done so, add authorized users to thefile realm of the Application Server as described inAdding Authorized Roles and Users.

  3. Open the project in NetBeans IDE by selecting File→Open Project.

  4. Browse to thetut-installjavaeetutorial5/examples/web/hello2_basicauth/ directory.

  5. Make sure that Open as Main Project is selected.

  6. Select Open Project.

  7. Right-clickhello2_basicauth in the Projects pane, then select Clean and Build.

  8. Right-clickhello2_basicauth in the Projects pane, then select Undeploy and Deploy.

  9. To run the servlet, follow the steps inRunning the Basic Authentication Servlet.

Building, Packaging, and Deploying the Servlet Basic Authentication Example Using Ant

To build, package, and deploy theweb/hello2_basicauth example using the Ant tool, followthese steps:

  1. If you have not already done so, follow the instructions inBuilding the Examples. This step is necessary to provide the Ant targets with the location of your tutorial and Application Server installations.

  2. If you have not already done so, add authorized users to thefile realm of the Application Server as described inAdding Authorized Roles and Users.

  3. From a terminal window or command prompt, change to thetut-install/javaeetutorial5/examples/web/hello2_basicauth/ directory.

  4. Build and package the web application by entering the following command at the terminal window or command prompt:

    ant

    This command usesweb.xml andsun-web.xml files, located in thetut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/ directory.

  5. To deploy the example using Ant, enter the following command at the terminal window or command prompt:

    ant deploy

    Thedeploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown inRunning the Basic Authentication Servlet.

  6. To run the web application, follow the steps inRunning the Basic Authentication Servlet.

Running the Basic Authentication Servlet

To run the web client, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in your web browser:

    http://localhost:8080/hello2_basicauth/greeting

    If you set the transport guarantee to CONFIDENTIAL as discussed inProtecting Passwords with SSL, you must load the application in a web browser usinghttps for the protocol, the HTTPS port that you specified during installation for the port (by default this port is 8181), and the context name for the application you wish to run. For the basic authentication example, you could run the example using the following URL:https://localhost:8181/hello2_basicauth/greeting.

  3. A default login form displays. Enter a user name and password combination that corresponds to a user that has already been created in thefile realm of the Application Server and has been assigned to the group ofuser, as discussed inAdding Authorized Roles and Users.

    Basic authentication is case-sensitive for both the user name and password, so enter the user name and password exactly as defined for the Application Server.

    If you enteredMy_Name as the name andMy_Pwd for the password, the server returns the requested resource if all of the following conditions are met:

    • There is a user defined for the Application Server with the user name ofMy_Name.

    • The user with the user name ofMy_Name has a password ofMy_Pwd defined for the Application Server.

    • The userMy_Name with the passwordMy_Pwd is assigned to the group ofuser on the Application Server.

    • The role ofhelloUser, as defined for the application, is mapped to the group ofuser, as defined for the Application Server.

    When these conditions are met, and the server has authenticated the user, the application will display as shown inFigure 30-9.

  4. Enter your name and click the Submit button. Because you have already been authorized, the name you enter in this step does not have any limitations. You have unlimited access to the application now.

    The application responds by saying “Hello” to you, as shown inFigure 30-10.

Figure 30-9 Running the Application

Screen shot of running basic authentication example showing text field for user to type name

Figure 30-10 The Running Basic Authentication Example

Screen shot of running basic authentication example showing response

Note -For repetitive testing of this example, you may need to close and reopenyour browser. You should also run theant clean andant undeploy targets orthe NetBeans IDE Clean and Build option to get a fresh start.


Troubleshooting the Basic Authentication Example

When doing iterative development with this web application, follow these steps if youare using NetBeans IDE:

  1. Close your web browser.

  2. Clean and recompile the files from the previous build by right-clickinghello2_basicauth and selecting Clean and Build.

  3. Redeploy the application by right-clickinghello2_basicauth and selecting Undeploy and Deploy.

  4. Open your web browser and reload the following URL:

    http://localhost:8080/hello2_basicauth/greeting

Follow these steps if you are using the Ant tool:

  1. Close your web browser.

  2. Undeploy the web application. To undeploy the application, use the following command in the directory:

    ant undeploy
  3. Clean out files from the previous build, using the following command:

    ant clean
  4. Recompile, repackage, and redeploy the application, using the following commands:

    ant ant deploy
  5. Open your web browser and reload the following URL:

    http://localhost:8080/hello2_basicauth/greeting

Example: Basic Authentication with JAX-WS

This section discusses how to configure a JAX-WS-based web service for HTTP basicauthentication. When a service that is constrained byHTTP basic authentication is requested, theserver requests a user name and password from the client and verifies thatthe user name and password are valid by comparing them against a databaseof authorized users.

If the topic of authentication is new to you, refer to thesection titledSpecifying an Authentication Mechanism. For an explanation of how basic authentication works, seeFigure 30-2.

For this tutorial, you will add the security elements to the JAX-WS serviceand client; build, package, and deploy the service; and then build and runthe client application.

This example service was developed by starting with an unsecured service,helloservice,which can be found in the directorytut-install/javaeetutorial5/examples/jaxws/helloservice and is discussed inCreating a Simple Web Service and Client with JAX-WS. You build on this simple application by adding the necessary elements tosecure the application using basic authentication. The example client used in this applicationcan be found attut-install/javaeetutorial5/examples/jaxws/simpleclient-basicauth, which only varies from the originalsimpleclientapplication in that it uses thehelloservice-basicauth endpoint instead of thehelloservice endpoint. Thecompleted version of the secured service can be found attut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth.

In general, the following steps are necessary to add basic authentication to aJAX-WS web service. In the example application included with this tutorial, many ofthese steps have been completed for you and are listed here simply toshow what needs to be done should you wish to create asimilar application.

  1. Create an application like the one inCreating a Simple Web Service and Client with JAX-WS. The example in this tutorial starts with that example and demonstrates adding basic authentication of the client to this application. The completed version of this application is located in the directoriestut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth andtut-install/javaeetutorial5/examples/jaxws/simpleclient-basicauth.

  2. If the port value was set to a value other than the default (8080), follow the instructions inSetting the Port to update the example files to reflect this change.

  3. If you have not already done so, follow the steps inBuilding the Examples for information on setting up your system to run the example.

  4. 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. If you have not already completed this step, refer to the sectionManaging Users and Groups on the Application Server for instructions.

  5. Modify the source code for the service,Hello.java, to specify which roles are authorized to access thesayHello (String name) method. This step is discussed inAnnotating the Service.

  6. Add security elements that specify that basic authentication is to be performed to the application deployment descriptor,web.xml. This step is discussed inAdding Security Elements to the Deployment Descriptor.

  7. Modify the runtime deployment descriptor,sun-web.xml, to map the role used in this application (basicUser) to a group defined on the Application Server (user). This step is discussed inLinking Roles to Groups.

  8. Build, package, and deploy the web service. SeeBuilding and Deployinghelloservice with Basic Authentication Using NetBeans IDE orBuilding and Deployinghelloservice with Basic Authentication Using Ant for the steps to accomplish this.

  9. Build and run the client application. SeeBuilding and Running thehelloservice Client Application with Basic Authentication Using NetBeans IDE orBuilding and Running thehelloservice Client Application with Basic Authentication Using Ant for the steps to accomplish this.

Annotating the Service

In this example, annotations are used to specify which users are authorized toaccess which methods of this service. In this simple example, the@RolesAllowedannotation is used to specify that users in the application role ofbasicUserare authorized access to thesayHello(String name) method. This application role must belinked to a group of users on the Application Server. Linking the rolesto groups is discussed inLinking Roles to Groups.

The source code for the original/helloservice application was modified as shown inthe following code snippet (modifications inbold). This file can be foundin the following location:

tut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth/src/java/helloservice/basicauth/endpoint/Hello.java

The code snippet is as follows:

package helloservice.basicauth.endpoint;import javax.jws.WebMethod;import javax.jws.WebService;import javax.annotation.security.RolesAllowed;@WebService()public class Hello {     private String message = new String("Hello, ");    @WebMethod()@RolesAllowed("basicUser")    public String sayHello(String name) {         return message + name + ".";    }}

The@RolesAllowed annotation specifies that only users in the role ofbasicUser willbe allowed to access thesayHello (String name) method. An@RolesAllowed annotation implicitly declares a rolethat will be referenced in the application, therefore, no@DeclareRoles annotation is required.

Adding Security Elements to the Deployment Descriptor

To enable basic authentication for the service, add security elements to the applicationdeployment descriptor,web.xml. The security elements that need to be added to thedeployment descriptor include the<security-constraint> and<login-config>elements. These security elements are discussed in moredetail inDeclaring Security Requirements in a Deployment Descriptor and in the Java Servlet Specification. The following code isadded to the original deployment descriptor to enable HTTP basic authentication. The resultingdeployment descriptor is located intut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth/web/WEB-INF/web.xml.

<?xml version="1.0" encoding="UTF-8"?><web-app     xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"     xmlns:xsi="http://www.w3.org/2001/XMLSchema"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <display-name>HelloService</display-name>    <listener>        <listener-class>            com.sun.xml.ws.transport.http.servlet.WSServletContextListener        </listener-class>    </listener>    <servlet>        <display-name>HelloService</display-name>        <servlet-name>HelloService</servlet-name>        <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>HelloService</servlet-name>        <url-pattern>/hello</url-pattern>    </servlet-mapping>    <session-config>        <session-timeout>30</session-timeout>    </session-config>    <security-constraint>        <display-name>SecurityConstraint</display-name>        <web-resource-collection>             <web-resource-name>WRCollection</web-resource-name>            <url-pattern>/hello</url-pattern>        </web-resource-collection>        <auth-constraint>            <role-name>basicUser</role-name>        </auth-constraint>        <user-data-constraint>            <transport-guarantee>NONE</transport-guarantee>        </user-data-constraint>    </security-constraint>    <login-config>        <auth-constraint>BASIC</auth-constraint>        <realm-name>file</realm-name>    </login-config></web-app>
Linking Roles to Groups

The role ofbasicUser has been defined for this application, but there isno group ofbasicUser defined for the Application Server. To map the rolethat is defined for the application (basicUser) to a group that is definedon the Application Server(user), add a<security-role-mapping> element to the runtime deployment descriptor,sun-web.xml, as shown below (modifications from the original file are inbold). The resultingruntime deployment descriptor is located intut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth/web/WEB-INF/sun-web.xml.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd"><sun-web-app error-url="">    <context-root>/helloservice</context-root>    <class-loader delegate="true"/><security-role-mapping><role-name>basicUser</role-name><group-name>user</group-name></security-role-mapping></sun-web-app>
Building and Deployinghelloservice with Basic Authentication Using NetBeans IDE

To build, package, and deploy thejaxws/helloservice-basicauth example using NetBeans IDE, follow thesesteps, or the steps described inBuilding, Packaging, and Deploying the Service.

  1. If you have not already done so, set up your system for running the tutorial examples by following the instructions inBuilding the Examples.

  2. If you haven’t already done so, set up an authorized user on the Application Server, assigned to the groupuser, as described inManaging Users and Groups on the Application Server.

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

  4. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jaxws/.

  5. Select thehelloservice-basicauth folder.

  6. Check the Open as Main Project and Open Required Projects check boxes.

  7. Click Open Project.

  8. In the Projects tab, right-click thehelloservice-basicauth project and select Clean and Build.

  9. In the Projects tab, right-click thehelloservice-basicauth project and select Undeploy and Deploy.

    This step builds and packages the application intohelloservice-basicauth.war, located intut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth/dist, and deploys this war file to your Application Server instance.

Building and Deployinghelloservice with Basic Authentication Using Ant

To build, package, and deploy thejaxws/helloservice-basicauth example using the Ant tool, followthese steps, or the steps described inBuilding, Packaging, and Deploying the Service.

  1. If you have not already done so, set up your system for running the tutorial examples by following the instructions inBuilding the Examples.

  2. If you haven’t already done so, set up an authorized user on the Application Server, assigned to the groupuser, as described inManaging Users and Groups on the Application Server.

  3. From a terminal window or command prompt, go to thetut-install/javaeetutorial5/examples/jaxws/helloservice-basicauth/ directory.

  4. Build, package, and deploy the JAX-WS service by entering the following at the terminal window or command prompt in thehelloservice-basicauth/ directory:

    ant all

You can test the service by selecting it in the Admin Consoleand choosing Test. For more information on how to do this, readTesting the Service without a Client.

Building and Running thehelloservice Client Application with Basic Authentication Using NetBeans IDE

To build and run the client application,simpleclient-basicauth, using NetBeans IDE, follow thesesteps. Thehelloservice-basicauth service must be deployed onto the Application Server before compilingthe client files. For information on deploying the service, readBuilding and Deployinghelloservice with Basic Authentication Using NetBeans IDE.

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

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

  3. Select thesimpleclient-basicauth folder.

  4. Check the Open as Main Project and Open Required Projects check boxes.

  5. Click Open Project.

  6. In the Projects tab, right-click thesimpleclient-basicauth project and select Clean and Build.

  7. In the Projects tab, right-click thesimpleclient-basicauth project and select Run.

    You will be prompted for your user name and password.

  8. Enter the user name 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 ofuser.

    If the username and password you enter are authorized, you will see the output of the application client in the Output pane.

The client displays the following output:

[echo] running application client container.[exec] Retrieving the port from the following service: helloservice.basicauth.endpoint.HelloService@c8769b[exec] Invoking the sayHello operation on the port.[exec] Hello, No Name.
Building and Running thehelloservice Client Application with Basic Authentication Using Ant

To build and run the client application,simpleclient-basicauth, using the Ant tool, followthese steps. The secured service must be deployed onto the Application Server beforeyou can successfully compile the client application. For more information on deploying theservice, readBuilding and Deployinghelloservice with Basic Authentication Using Ant.

  1. Build the client by changing to the directorytut-install/examples/jaxws/simpleclient-basicauth/ and entering the following at the terminal window or command prompt:

    ant

    This command calls thedefault target, which builds and packages the application into a JAR file,simpleclient-basicauth.jar, located in the/dist directory.

  2. Run the client by entering the following at the terminal window or command prompt:

    ant run

    A Login for User dialog displays.

  3. Enter a user name and password that correspond to a user set up on the Application Server with a group ofuser. Click OK.

The client displays the following output:

[echo] running application client container.[exec] Retrieving the port from the following service: helloservice.basicauth.endpoint.HelloService@c8769b[exec] Invoking the sayHello operation on the port.[exec] Hello, No Name.
PreviousContentsNext

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


[8]ページ先頭

©2009-2025 Movatter.jp