Spring RestController AOP 自定义每个方法的访问规则

Spring RestController AOP custom access rules for each method

我有一个 API class,其中几种方法有不同的访问规则要求,例如只有群组中的用户可以访问此 API,或者此 API 允许未经身份验证的访问。

在 Spring 中处理此问题的最佳做法是什么?

我原本希望使用 AOP 通过自定义注释来处理这个问题,但在调查之后似乎不可能。例如

@RequestMapping("/getGroup")
@GroupMembersOnly

我现在开始工作了。

注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
@Documented
public @interface GroupMembersOnly {

}

我的配置中缺少的部分 class

@Aspect
public class AopConfiguration{
...
@Around("execution(* *(..)) && @annotation(groupMembersOnly)")
  public Object around(ProceedingJoinPoint point, GroupMembersOnly groupMembersOnly) throws Throwable {

    //do something, e.g. use point.getArgs()
    //to do something with the menthod arguments

    //give control back to method
    return point.proceed();
}
}

然后在我要拦截的方法上

@RequestMapping("/getGroup")
@GroupMembersOnly
public ResponseEntity<List<String>> readMembers(HttpServletRequest request, HttpServletResponse response) {
/*Add HttpServletRequest request, HttpServletResponse response arguments if you 
want to do something with them in the interceptor*/