需求:我们需要对未审核通过的企业限制api请求操作,防止恶意攻击
方案:controller 自定义注解 切面安全验证
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.添加一个自定义注解
package com.sinopharm.handler;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
*
* @author GAO
* @date 2018年4月10日
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
}
3.编写切面类(省略相关业务代码)
@Aspect
@Component
public class SecurityVerificationHandler {
private static final Logger logger = LoggerFactory.getLogger(SecurityVerificationHandler.class);
@Before("execution(* com.***.controller..*(..)) && @annotation(com.***.MyAnnotation)")
public void begin(JoinPoint point) throws IOException {
logger.info("@Before:权限检查...");
logger.info("@Before:目标方法为:" + point.getSignature().getDeclaringTypeName() + "" + point.getSignature().getName());
logger.info("@Before:参数为:" + Arrays.toString(point.getArgs()));
logger.info("@Before:被织入的目标对象为:" + point.getTarget());
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
if (method.equals("GET")) {
String queryString = request.getQueryString();
String[] strings = queryString.split("&");
for (String string : strings) {
String[] strs = string.split("=");
....
}
} else if (method.equals("POST")) {
String param = Arrays.toString(point.getArgs());
....
}
}
4.在需要的controller上添加注解
@MyAnnotation
@PostMapping("/***")
public Object ***(@RequestBody Map<String, Object> params) {
...
}
附上切面编程相关说明:
使用注解
@Aspect 指定一个类为切面类
@Pointcut("execution(* com.sinopharm.controller..*(..))") 指定切入点表达式
@Before("pointCut_()") 前置通知: 目标方法之前执行
@After("pointCut_()") 后置通知:目标方法之后执行(始终执行)
@AfterReturning("pointCut_()") 返回后通知: 执行方法结束前执行(异常不执行)
@AfterThrowing("pointCut_()") 异常通知: 出现异常时候执行
@Around("pointCut_()") 环绕通知: 环绕目标方法执行