Spring Boot 3.3自定义@RequiresAnyRole注解无法访问#root.annotation求助
自定义权限注解的SpEL表达式参数获取问题
需求目标
我想要创建自定义注解,替代以下标准权限校验方式:
@RequiresAnyRole({"UPDATE_DATA"}) @PreAuthorize("hasAnyAuthority('UPDATE_DATA')")
实现后可构建业务级安全注解,并支持方法级权限覆盖。当前使用Spring Boot 3.3版本,自定义注解代码如下:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @PreAuthorize("@securityHelper.hasAnyListedAuthority(authentication, #root.annotation.value)") public @interface RequiresAnyRole { String[] value() default {}; }
运行报错
使用上述注解时,抛出EL表达式解析错误:
EL1008E: Property or field 'annotation' cannot be found on object of type 'org.springframework.security.access.expression.method.MethodSecurityExpressionRoot' - maybe not public or not valid?"}
尝试的失败方案
GitLab Duo提供的替代方案因使用this同样失败,对应的SpEL表达式如下:
@PreAuthorize("@securityHelper.hasAnyListedAuthority(authentication, T(org.springframework.security.access.expression.method.MethodSecurityExpressionRoot).this.returnObject.getClass().getMethod(T(org.springframework.security.access.expression.method.MethodSecurityExpressionRoot).this.filterObject).getAnnotation(T(com.barclays.spone.loans.security.annotation.RequiresAnyRole)).value())")
校验工具方法
权限校验的工具方法实现如下:
public boolean hasAnyListedAuthority(Authentication auth, String[] authorities) { Set<String> userAuthorities = AuthorityUtils.authorityListToSet(auth.getAuthorities()); return Arrays.stream(authorities) .anyMatch(userAuthorities::contains); }
问题
如何正确获取自定义注解的参数并传入SpEL表达式中?
内容的提问来源于stack exchange,提问作者Leos Literak
相关产品推荐
相关产品推荐

