Annotation Interface RequiresAnyRole
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 ElementsModifier and TypeOptional ElementDescriptionbooleanDetermines whether an exception should be thrown when the authorization check fails.String[]One or more role names (case-sensitive) that grant access.
-
Element Details
-
value
String[] valueOne 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 throwIfUnauthorizedDetermines 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:UnauthenticatedException– if no authenticated user is presentUnauthorizedException– if the user is present but lacks required roles
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
-