63

我正在开发一个 Java 企业应用程序,目前正在做 Java EE 安全工作,以限制对特定用户的特定功能的访问。我配置了应用程序服务器和所有内容,现在我使用 RolesAllowed-annotation 来保护方法:

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

当我使用这样的注释时,它工作正常:

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

但这不是我想要的,因为我必须在这里使用字符串,重构变得很困难,并且可能会发生拼写错误。因此,我不想使用字符串,而是使用枚举值作为此注释的参数。枚举看起来像这样:

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;
    }
}

所以我尝试使用 Enum 作为这样的参数:

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

但是随后我得到以下编译器错误,尽管 Enum.name 只返回一个字符串(它始终是常量,不是吗?)。

注解属性 RolesAllowed.value 的值必须是常量表达式`

我尝试的下一件事是在我的枚举中添加一个额外的最终字符串:

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

但这也不能作为参数工作,导致相同的编译器错误:

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

我怎样才能实现我想要的行为?我什至实现了自己的拦截器来使用自己的注释,这很漂亮,但是对于这样的小问题来说代码行太多了。

免责声明

这个问题最初是一个Scala问题。我发现 Scala 不是问题的根源,所以我首先尝试在 Java 中执行此操作。

4

5 回答 5

37

我认为您使用枚举的方法不会奏效。我发现如果我将STUDENT_ROLE最后一个示例中的字段更改为常量字符串,而不是表达式,编译器错误就会消失:

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

但是,这意味着枚举值不会在任何地方使用,因为您将在注释中使用字符串常量。

在我看来,如果你的RoleType类只包含一堆静态的 final String 常量,你会更好。


要了解您的代码未编译的原因,我查看了Java 语言规范(JLS)。注释的 JLS指出,对于具有类型T和值V的参数的注释,

如果T是原始类型或String,则V是常量表达式。

一个常量表达式包括,除其他外,

TypeName形式的限定名称。 引用常量变量的标识符

并且一个常量变量被定义为

一个原始类型或类型的变量,String它是最终的并使用编译时常量表达式进行初始化

于 2010-07-17T19:01:29.807 回答
35

这个怎么样?

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;
    }
}

在注释中,您可以像这样使用它

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

一个小问题是,对于任何修改,我们需要在两个地方进行更改。但由于它们在同一个文件中,因此不太可能错过。作为回报,我们得到了不使用原始字符串和避免复杂机制的好处。

或者这听起来完全愚蠢?:)

于 2017-08-21T14:58:08.273 回答
11

这是一个使用附加接口和元注释的解决方案。我已经包含了一个实用程序类来帮助进行反射以从一组注释中获取角色类型,并对其进行一些测试:

/**
 * 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());
    }
}
于 2011-10-06T18:29:44.310 回答
2

我通过使用 Lombok 注释解决了这个问题FieldNameConstants

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

接下来,您可以按如下方式使用它:

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

   @PostMapping("user")
   public void deleteUser(...) {
       ...
   }
}
于 2021-07-21T14:39:10.247 回答
0

我通过添加注释@RoleTypesAllowed和添加元数据源解决了这个问题。如果只需要支持一种枚举类型,这将非常有效。有关多种枚举类型,请参阅 anomolos 的帖子。

下面RoleType是我的角色枚举。

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

然后我将以下元数据源添加到 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;
  }
}
于 2019-01-21T12:26:36.783 回答