background image

DeclareRoles Annotation

<< Declaring Roles Using Annotations | Security Requirements forWeb Applications >>
<< Declaring Roles Using Annotations | Security Requirements forWeb Applications >>

DeclareRoles Annotation

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.
For example, during application assembly, the assembler creates security roles for the
application and associates these roles with available security mechanisms. The assembler then
resolves the security role references in individual servlets and JSP pages by linking them to roles
defined for the application. For example, the assembler could map the security role reference
cust
to the security role with the role name bankCustomer using the <security-role-ref>
element of the deployment descriptor.
Declaring Roles Using Annotations
The preferred method of declaring roles referenced in an application is to use the
@DeclareRoles
annotation. The following code sample provides an example that specifies that
the roles of j2ee and guest will be used in the application, and verifies that the user is in the role
of j2ee before printing out Hello World.
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.security.DeclareRoles;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@DeclareRoles({"j2ee", "guest"})
public class Servlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType(
"text/html");
PrintWriter out = resp.getWriter();
out.println(
"<HTML><HEAD><TITLE>Servlet Output</TITLE>
</HEAD><BODY>
");
if (req.isUserInRole("j2ee") && !req.isUserInRole("guest")) {
out.println(
"Hello World");
} else {
out.println(
"Invalid roles");
}
out.println(
"</BODY></HTML>");
}
}
Checking Caller Identity Programmatically
Chapter 30 · Securing Web Applications
847