控制器方法上的自定义注释以拦截请求和验证

use*_*r09 7 spring annotations httprequest spring-boot

我想创建一个注释,我将在控制器方法上使用它来验证对资源的访问。我编写了拦截器来拦截请求,还编写了代码来为它们的独立场景创建注释。现在我想拦截请求并获取注释中提供的值以进行进一步处理。

理想情况下

@RequestMapping("/release")
@ValidateAction("resource","release") //custom annotation that will accept two strings
public ResponseEntity releaseSoftware(Request request){
}
Run Code Online (Sandbox Code Playgroud)

从上面我必须从@ValidateAction 中获取这两个值并向另一个授权服务器发送请求以授权该操作,如果用户有权访问它(请求包含将用于授权的 oauth 访问令牌)并返回 true 如果用户有权访问,否则抛出 AcceeDenied 异常。任何人都可以指出我在 Spring 引导环境中正确的方向吗

pvp*_*ran 8

实现这一点的最佳方法是使用 Spring AOP Aspects。

让我们假设您有这样的注释

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateAction {

  String resource();
  String release();
}
Run Code Online (Sandbox Code Playgroud)

然后像这样写一个Aspect

@Aspect
@Component
public class AspectClass {

  @Around(" @annotation(com.yourpackage.ValidateAction)")
  public Object validateAspect(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();

    ValidateAction validateAction = method.getAnnotation(ValidateAction.class);
    String release = validateAction.release();
    String resource = validateAction.resource();


    // Call your Authorization server and check if all is good
    if( hasAccess)
      pjp.proceed();

    .......
  }
}
Run Code Online (Sandbox Code Playgroud)

@ValidateAction调用任何带有注释的方法时,控件将转到 validateAspect 方法。在这里您可以捕获如图所示的注释值并进行必要的检查。

确保您具有所需的正确依赖项和这些导入

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
Run Code Online (Sandbox Code Playgroud)