Annotation Interface RequiresAnyRole


Declares role-based access control for message handlers or payload types.

When placed on a handler method, class, or package, or on the payload class the @RequiresAnyRole annotation restricts invocation of that handler to users possessing at least one of the specified roles. If the current user (or the user associated with the incoming message) lacks a matching role, an exception is thrown or the handler is silently skipped, depending on the value of throwIfUnauthorized(). Silent skipping allows other eligible handlers to take over, enabling flexible delegation.

This annotation supports meta-annotations. It can be applied to a custom annotation that expresses roles using an enum, allowing more structured or type-safe role definitions. Role names are obtained from the toString() method of the enum.

Example (on handler method):


 @HandleCommand
 @RequiresAnyRole({"admin", "editor"})
 void handle(UpdateArticle command) {}
 

Example (on payload class):


 @RequiresAnyRole("admin")
 public record DeleteAccount(String userId) {}
 

Meta-annotation usage (with enum roles):


 @RequiresAnyRole
 @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD})
 public @interface RequiresRole {
     Role[] value();
 }
 
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    boolean
    Determines whether an exception should be thrown when the authorization check fails.
    One or more role names (case-sensitive) that grant access.
  • Element Details

    • value

      String[] value
      One or more role names (case-sensitive) that grant access. At least one of the listed roles must be held by the user for access to be granted.
      Default:
      {}
    • throwIfUnauthorized

      boolean throwIfUnauthorized
      Determines whether an exception should be thrown when the authorization check fails.

      If true (the default), an exception will be thrown when the user is unauthorized:

      If false, the annotated handler or message will be silently skipped instead. This opt-out strategy is useful for conditionally invoked handlers where fallback behavior or a timeout is preferred.

      Defaults to true.

      Default:
      true