Use Enum type as a value parameter for @RolesAllowed-Annotation

JavaJakarta EeEnumsAnnotationsJava Ee-6

Java Problem Overview


I'm developing a Java enterprise application, currently doing Java EE security stuff to restrict access for particular functions to specific users. I configured the application server and everything, and now I'm using the RolesAllowed-annotation to secure the methods:

@Documented
@Retention (RUNTIME)
@Target({TYPE, METHOD})
public @interface RolesAllowed {
    String[] value();
}

When I use the annotation like this, it works fine:

@RolesAllowed("STUDENT")
public void update(User p) { ... }

But this is not what I want, as I have to use a String here, refactoring becomes hard, and typos can happen. So instead of using a String, I would like to use an Enum value as a parameter for this annotation. The Enum looks like this:

public enum RoleType {
    STUDENT("STUDENT"),
    TEACHER("TEACHER"),
    DEANERY("DEANERY");

    private final String label;

    private RoleType(String label) {
        this.label = label;
    }

    public String toString() {
        return this.label;
    }
}

So I tried to use the Enum as a parameter like this:

@RolesAllowed(RoleType.DEANERY.name())
public void update(User p) { ... }

But then I get the following compiler error, although Enum.name just returns a String (which is always constant, isn't it?).

> The value for annotation attribute RolesAllowed.value must be a constant expression`

The next thing I tried was to add an additional final String to my Enum:

public enum RoleType {
    ...
    public static final String STUDENT_ROLE = STUDENT.toString();
    ...
}

But this also doesn't work as a parameter, resulting in the same compiler error:

// The value for annotation attribute RolesAllowed.value must be a constant expression
@RolesAllowed(RoleType.STUDENT_ROLE)

How can I achieve the behavior I want? I even implemented my own interceptor to use my own annotations, which is beautiful, but far too much lines of codes for a little problem like this.

DISCLAIMER

This question was originally a Scala question. I found out that Scala is not the source of the problem, so I first try to do this in Java.

Java Solutions


Solution 1 - Java

I don't think your approach of using enums is going to work. I found that the compiler error went away if I changed the STUDENT_ROLE field in your final example to a constant string, as opposed to an expression:

public enum RoleType { 
  ...
  public static final String STUDENT_ROLE = "STUDENT";
  ...
}

However, this then means that the enum values wouldn't be used anywhere, because you'd be using the string constants in annotations instead.

It seems to me that you'd be better off if your RoleType class contained nothing more than a bunch of static final String constants.


To see why your code wasn't compiling, I had a look into the http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html">Java Language Specification (JLS). The JLS for http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.7">annotations</a> states that for an annotation with a parameter of type T and value V,

> if T is a primitive type or String, V is a constant expression.

A http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313">constant expression includes, amongst other things, > Qualified names of the form TypeName . Identifier that refer to constant variables

and a http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#10931">constant variable is defined as

> a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression

Solution 2 - Java

How about this?

public enum RoleType {
    STUDENT(Names.STUDENT),
    TEACHER(Names.TEACHER),
    DEANERY(Names.DEANERY);

    public class Names{
        public static final String STUDENT = "Student";
        public static final String TEACHER = "Teacher";
        public static final String DEANERY = "Deanery";
    }

    private final String label;

    private RoleType(String label) {
        this.label = label;
    }

    public String toString() {
        return this.label;
    }
}

And in annotation you can use it like

@RolesAllowed(RoleType.Names.DEANERY)
public void update(User p) { ... }

One little concern is, for any modification, we need to change in two places. But since they are in same file, its quite unlikely to be missed. In return, we are getting the benefit of not using raw strings and avoiding the sophisticated mechanism.

Or this sounds totally stupid? :)

Solution 3 - Java

Here's a solution using an additional interface and a meta-annotation. I've included a utility class to help do the reflection to get the role types from a set of annotations, and a little test for it:

/**
 * empty interface which must be implemented by enums participating in
 * annotations of "type" @RolesAllowed.
 */
public interface RoleType {
    public String toString();
}

/** meta annotation to be applied to annotations that have enum values implementing RoleType. 
 *  the value() method should return an array of objects assignable to RoleType*.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ANNOTATION_TYPE})
public @interface RolesAllowed { 
    /* deliberately empty */ 
}

@RolesAllowed
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD})
public @interface AcademicRolesAllowed {
    public AcademicRoleType[] value();
}

public enum AcademicRoleType implements RoleType {
    STUDENT, TEACHER, DEANERY;
    @Override
    public String toString() {
        return name();
    }
}


public class RolesAllowedUtil {

    /** get the array of allowed RoleTypes for a given class **/
    public static List<RoleType> getRoleTypesAllowedFromAnnotations(
            Annotation[] annotations) {
        List<RoleType> roleTypesAllowed = new ArrayList<RoleType>();
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().isAnnotationPresent(
                    RolesAllowed.class)) {
                RoleType[] roleTypes = getRoleTypesFromAnnotation(annotation);
                if (roleTypes != null)
                    for (RoleType roleType : roleTypes)
                        roleTypesAllowed.add(roleType);
            }
        }
        return roleTypesAllowed;
    }

    public static RoleType[] getRoleTypesFromAnnotation(Annotation annotation) {
        Method[] methods = annotation.annotationType().getMethods();
        for (Method method : methods) {
            String name = method.getName();
            Class<?> returnType = method.getReturnType();
            Class<?> componentType = returnType.getComponentType();
            if (name.equals("value") && returnType.isArray()
                    && RoleType.class.isAssignableFrom(componentType)) {
                RoleType[] features;
                try {
                    features = (RoleType[]) (method.invoke(annotation,
                            new Object[] {}));
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Error executing value() method in "
                                    + annotation.getClass().getCanonicalName(),
                            e);
                }
                return features;
            }
        }
        throw new RuntimeException(
                "No value() method returning a RoleType[] type "
                        + "was found in annotation "
                        + annotation.getClass().getCanonicalName());
    }

}

public class RoleTypeTest {

    @AcademicRolesAllowed({DEANERY})
    public class DeaneryDemo {

    }

    @Test
    public void testDeanery() {
        List<RoleType> roleTypes = RolesAllowedUtil.getRoleTypesAllowedFromAnnotations(DeaneryDemo.class.getAnnotations());
        assertEquals(1, roleTypes.size());
    }
}

Solution 4 - Java

I solved this by using Lombok annotation FieldNameConstants :

@FieldNameConstants(onlyExplicitlyIncluded = true)
public enum EnumBasedRole {
    @FieldNameConstants.Include ADMIN,
    @FieldNameConstants.Include EDITOR,
    @FieldNameConstants.Include READER;
}

Next you can use it as follow :

@RestController
@RequestMapping("admin")
@RolesAllowed(EnumBasedRole.Fields.ADMIN)
public class MySecuredController {

   @PostMapping("user")
   public void deleteUser(...) {
       ...
   }
}

Solution 5 - Java

I solved this problem by adding an annotation @RoleTypesAllowed and adding a metadata source. This works really well if there is just one enum type that needs to be supported. For multiple enum types, see anomolos's post.

In the below RoleType is my role enum.

@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RoleTypesAllowed {
  RoleType[] value();
}

Then I added the following metadata source to spring...

@Slf4j
public class CemsRolesAllowedMethodSecurityMetadataSource
    extends AbstractFallbackMethodSecurityMetadataSource {

  protected Collection<ConfigAttribute> findAttributes(Class<?> clazz) {
    return this.processAnnotations(clazz.getAnnotations());
  }

  protected Collection<ConfigAttribute> findAttributes(Method method, Class<?> targetClass) {
    return this.processAnnotations(AnnotationUtils.getAnnotations(method));
  }

  public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
  }

  private List<ConfigAttribute> processAnnotations(Annotation[] annotations) {
    if (annotations != null && annotations.length != 0) {
      List<ConfigAttribute> attributes = new ArrayList();

      for (Annotation a : annotations) {
        if (a instanceof RoleTypesAllowed) {
          RoleTypesAllowed ra = (RoleTypesAllowed) a;
          RoleType[] alloweds = ra.value();
          for (RoleType allowed : alloweds) {
            String defaultedAllowed = new RoleTypeGrantedAuthority(allowed).getAuthority();
            log.trace("Added role attribute: {}", defaultedAllowed);
            attributes.add(new SecurityConfig(defaultedAllowed));
          }
          return attributes;
        }
      }
    }
    return null;
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWolkenarchitektView Question on Stackoverflow
Solution 1 - JavaLuke WoodwardView Answer on Stackoverflow
Solution 2 - JavaSamironView Answer on Stackoverflow
Solution 3 - JavaanomolosView Answer on Stackoverflow
Solution 4 - JavaXoddXView Answer on Stackoverflow
Solution 5 - JavaJohn BView Answer on Stackoverflow