The Java EE 5 Tutorial

Specifying the Security Constraint

This example takes a very simple servlet-based web application and adds basic authentication to this application. The servlet is basically the same as the servlet used in the example described in Web Modules, with the exception of the annotations added and discussed in Declaring 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:

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

The following sample code shows the security elements for the deployment descriptor used in this example of basic authentication, which can be found in tut-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 can be found in Specifying Security Constraints.

Protecting Passwords with SSL

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

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