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.  JavaServerTM Faces Technology

5.  Introduction to Facelets

6.  Unified Expression Language

7.  Using JavaServerTM Faces Technology in Web Pages

8.  Using Converters, Listeners and Validators

9.  Developing With JavaServerTM Faces Technology

10.  Java Servlet Technology

Part III Web Services

11.  Introduction to Web Services

12.  Building Web Services with JAX-WS

13.  Building RESTful Web Services with JAX-RS and Jersey

Part IV Enterprise Beans

14.  Enterprise Beans

15.  Getting Started with Enterprise Beans

16.  Running the Enterprise Bean Examples

Part V Contexts and Dependency Injection for the JavaTM EE Platform

17.  Introduction to Contexts and Dependency Injection for the JavaTM EE Platform

18.  Running the Basic Contexts and Dependency Injection Examples

Part VI Persistence

19.  Introduction to the Java Persistence API

20.  Running the Persistence Examples

21.  The Java Persistence Query Language

22.  Creating Queries Using the Criteria API

Part VII Security

23.  Introduction to Security in the Java EE Platform

24.  Getting Started Securing Enterprise Applications

25.  Getting Started Securing Web Applications

Overview of Web Application Security

Using Deployment Descriptors to Secure Web Applications

Introduction to Web Application Deployment Descriptors

Specifying Security Constraints

Specifying a Web Resource Collection

Specifying an Authorization Constraint

Specifying a Secure Connection

Specifying Separate Security Constraints for Different Resources

Specifying an Authentication Mechanism

HTTP Basic Authentication

Form-Based Authentication

HTTPS Client Authentication

Digest Authentication

Working with Security Roles

Reviewing Security Concepts

Declaring Security Roles

Mapping Security Roles to Enterprise Server Groups

Using Message Security with Web Applications

Examples: Securing Web Applications

Setting Up Your System for Running the Security Examples

Example: Basic Authentication with a Servlet

Specifying Security in the Deployment Descriptor

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 Deploying helloservice with Basic Authentication Using NetBeans IDE

Building and Deploying helloservice with Basic Authentication Using Ant

Building and Running the helloservice Client Application with Basic Authentication Using NetBeans IDE

Building and Running the helloservice Client Application with Basic Authentication Using Ant

Example: Form-Based Authentication with a Servlet

Creating the Login Form and the Error Page

Specifying Security in the Deployment Descriptor

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

Part VIII JavaTM EE Supporting Technologies

26.  Introduction to JavaTM EE Supporting Technologies

27.  Transactions

28.  Resource Connections

Index

 

Using Programmatic Security with Web Applications

Programmatic security is used by security-aware applications when declarative security alone is not sufficient to express the security model of the application. The following topics are discussed in this section:

Authenticating Users Programmatically

Servlet 3.0 specifies the following methods of the HttpServletRequest interface that enable you to authenticate users for a web application programmatically:

  • authenticate

    The authenticate method allows an application to instigate authentication of the request caller by the container from within an unconstrained request context. A login dialog box displays and collects the user's name and password for authentication purposes.

  • login

    The login method allows an application to collect username and password information as an alternative to specifying form-based authentication in an application deployment descriptor.

  • logout

    The logout method is provided to allow an application to reset the caller identity of a request.

The following example code shows how to use the login and logout methods:

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="TutorialServlet", urlPatterns={"/TutorialServlet"})
public class TutorialServlet extends HttpServlet {
    @EJB
    private ConverterBean converterBean;

    /**
     * Processes requests for both HTTP <code>GET</code> 
        * and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, 
            HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet TutorialServlet</title>");
            out.println("</head>");
            out.println("<body>");
            request.login("TutorialUser", "TutorialUser");
            BigDecimal result = converterBean.dollarToYen(new BigDecimal("1.0"));
            out.println("<h1>Servlet TutorialServlet result of dollarToYen= " + result + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            request.logout();
            out.close();
        }
    }
}

This code sample shows how to use the authenticate method:

package com.sam.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            request.authenticate(response);
            out.println("Authenticate Successful");

        } finally {
            out.close();
        }
    } 

Checking Caller Identity Programmatically

In general, security management should be enforced by the container in a manner that is transparent to the web component. The security API described in this section should be used only in the less frequent situations in which the web component methods need to access the security context information.

Servlet 3.0 specifies the following methods of the HttpServletRequest interface that enable you to verify a caller's identity programmatically, and to use that information to grant or deny access to data:

  • The HttpServletRequest interface provides the following methods that enable you to access security information about the component’s caller:getRemoteUser: Determines the user name with which the client authenticated. The getRemoteUser method returns the name of the remote user (that is, the caller) associated by the container with the request. If no user has been authenticated, this method returns null.

  • isUserInRole: Determines whether a remote user is in a specific security role. If no user has been authenticated, this method returns false. This method expects a String user role-name parameter.

    The <security-role-ref> element should be declared in the deployment descriptor with a <role-name> sub-element containing the role name to be passed to the method. Using security role references is discussed in Declaring and Linking Role References.

  • getUserPrincipal: Determines the principal name of the current user and returns a java.security.Principal object. If no user has been authenticated, this method returns null. Calling the getName method on the Principal returned by getUserPrincipal returns the name of the remote user.

Your application can make business logic decisions based on the information obtained using these APIs.

Example Code for Programmatic Security

The following code demonstrates the use of programmatic security for the purposes of programmatic login.

package enterprise.programmatic_login;

import java.io.*;
import java.net.*;

import javax.annotation.security.DeclareRoles;
import javax.servlet.*;
import javax.servlet.http.*;

@DeclareRoles("javaee6user")
public class LoginServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP GET and POST methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, 
                 HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String userName = request.getParameter("txtUserName");
            String password = request.getParameter("txtPassword");
            
            out.println("Before Login"+"<br><br>");
            out.println("IsUserInRole?.." + request.isUserInRole("javaee6user")+"<br>");
            out.println("getRemoteUser?.." + request.getRemoteUser()+"<br>");
            out.println("getUserPrincipal?.." + request.getUserPrincipal()+"<br>");
            out.println("getAuthType?.." + request.getAuthType()+"<br><br>");
            
            try {
            request.login(userName, password); 
            }catch(ServletException ex) {
                out.println("Login Failed with a ServletException.." + 
                        ex.getMessage());
                return;
            }
            out.println("After Login..."+"<br><br>");
            out.println("IsUserInRole?.." + request.isUserInRole("javaee6user")+"<br>");
            out.println("getRemoteUser?.." + request.getRemoteUser()+"<br>");
            out.println("getUserPrincipal?.." + request.getUserPrincipal()+"<br>");
            out.println("getAuthType?.." + request.getAuthType()+"<br><br>");
            
            request.logout();
            out.println("After Logout..."+"<br><br>");
            out.println("IsUserInRole?.." + request.isUserInRole("javaee6user")+"<br>");
            out.println("getRemoteUser?.." + request.getRemoteUser()+"<br>");
            out.println("getUserPrincipal?.." + request.getUserPrincipal()+"<br>");
            out.println("getAuthType?.." + request.getAuthType()+"<br>");
            
            
        } finally {
            out.close();
        }
    }

       /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
}

This servlet displays the name of the user who is currently logged in, then prompts a user for login, and prints out the information again, then logs out the user and prints the information again in order to demonstrate the effect of the login and logout methods. The application deployment descriptor, web.xml, includes a login-config element that specifies basic authentication. The runtime deployment descriptor, sun-web.xml, includes a role-mapping of the user of the application to a group of the same name on the Enterprise Server.

Declaring and Linking Role References

A security role reference defines a mapping between the name of a role that is called from a web component using isUserInRole(String role) and the name of a security role that has been defined for the application. If no <security-role-ref> element is declared in a deployment descriptor, and the isUserInRole method is called, the container defaults to checking the provided role name against the list of all security roles defined for the web application. Using the default method instead of using the security-role-ref element limits your flexibility to change role names in an application without also recompiling the servlet making the call.

The security-role-ref element is used when an application uses the HttpServletRequest.isUserInRole(String role) method. The value passed to the isUserInRole method is a String representing the role name of the user. The value of the role-name element must be the String used as the parameter to the HttpServletRequest.isUserInRole(String role) method. The role-link must contain the name of one of the security roles defined in the security-role elements. The container uses the mapping of security-role-ref to security-role when determining the return value of the call.

For example, to map the security role reference cust to the security role with role name bankCustomer, the syntax would be:

<servlet>
...
    <security-role-ref>
        <role-name>cust</role-name>
        <role-link>bankCustomer</role-link>
    </security-role-ref>
...
</servlet>

In this case, if the servlet called by a user belonging to the bankCustomer security role made the API call, isUserInRole("cust") would return true.

The <role-link> element in the security-role-ref element must match a <role-name> defined in the <security-role> element of the same web.xml deployment descriptor, as shown here:

<security-role>
    <role-name>bankCustomer</role-name>
</security-role>

A security role reference, including the name defined by the reference, is scoped to the component whose deployment descriptor contains the security-role-ref deployment descriptor element.