background image

Specifying the Security Constraint

<< Declaring Security Roles | Protecting Passwords with SSL >>
<< Declaring Security Roles | Protecting Passwords with SSL >>

Specifying the Security Constraint

The following section of the
tut-install/javaeetutorial5/examples/web/hello2_basicauth/src/servlets/
GreetingServlet.java
file contains the code necessary to declare that the role of helloUser 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 the deployment
descriptor. If you prefer to declare security roles this way, read
"Declaring Roles Using
Deployment Descriptor Elements" on page 848
.
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" on page 81
, with the exception of the annotations added and discussed in
"Declaring Security Roles" on page 878
.
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 in
"Declaring Security Requirements in a
Deployment Descriptor" on page 851
.
Examples: Securing Web Applications
Chapter 30 · Securing Web Applications
879