The Java EE 5 Tutorial

Declaring Security Roles Using Annotations

The @DeclareRoles annotation is specified on a bean class, where it serves to declare roles that can be tested by calling isCallerInRole from within the methods of the annotated class.

You declare the security roles referenced in the code using the @DeclareRoles annotation. When declaring the name of a role used as a parameter to the isCallerInRole(String roleName) method, the declared name must be the same as the parameter value. You can optionally provide a description of the named security roles in the description element of the @DeclareRoles annotation.

The following code snippet demonstrates the use of the @DeclareRoles annotation. In this example, the @DeclareRoles annotation indicates that the enterprise bean AardvarkPayroll makes the security check using isCallerInRole("payroll") to verify that the caller is authorized to change salary data. The security role reference is scoped to the session or entity bean whose declaration contains the @DeclareRoles annotation.

@Stateless public class PayrollBean implements Payroll {
    @Resource SessionContext ctx;

    public void updateEmployeeInfo(EmplInfo info) {

        oldInfo = ... read from database;

        // The salary field can be changed only by callers
        // who have the security role "payroll"
        if (info.salary != oldInfo.salary &&
            !ctx.isCallerInRole("payroll")) {
                throw new SecurityException(...);

The syntax for declaring more than one role is as shown in the following example:

@DeclareRoles({"Administrator", "Manager", "Employee"})