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

时间:2018-05-30 14:38:52

标签: spring spring-boot annotations httprequest

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

理想地

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

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

2 个答案:

答案 0 :(得分:3)

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

我们假设您有一个像这样的注释

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

  String resource();
  String release();
}

然后写一个像这样的方面

@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();

    .......
  }
}

当调用任何使用@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;

答案 1 :(得分:1)

您可以使用Spring AOP

执行此操作

首先,添加spring-aop依赖项:

compile 'org.springframework.boot:spring-boot-starter-aop' // Mine using gradle

@Configuration课程中,添加@EnableAspectJAutoProxy

@Configuration
@EnableAspectJAutoProxy
public class Application {
   ....
}

创建注释处理程序:

@Aspect
@Component // This @Component is required in spring aop
public class ValidateActionHandler {
    @Around("execution(@your.path.ValidateAction * *(..)) && @annotation(validateAction)")
    public Object doValidate(ProceedingJoinPoint pjp, ValidateAction retryConfig) throws Throwable {
       // Your logic here
       // then
       return pjp.proceed();
    }
}
相关问题