java实现接口防刷

【java实现接口防刷】一、接口的安全性
 

  • 1、防伪装攻击
  • 处理方式:接口防刷
  • 出现的的情况:公共网络环境中,第三方有意或者恶意调用我们的接口
  • 2、防篡改攻击
  • 处理方式:签名机制
  • 出现情况:请求头/查询字符串/内容 在传输中来修改其内容
  • 3、防重放攻击
  • 处理方式:接口时效性
  • 出现情况:请求被截获,稍后被重放或多次重放
  • 4、防止止数据信息泄露
  • 处理方式:接口加密(对称加解密)
  • 出现情况:截获用户登录请求,主要是截获账号密码
 
二、实现自定义的注解
import JAVA.lang.Annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import static java.lang.annotation.ElementType.METHOD;@Retention(RetentionPolicy.RUNTIME)@Target(METHOD)@Documentedpublic @interface RateLimit {String cycle() default "5"; //请求等待的时间String number() default "1"; //短时间内多少次的请求String msg() default "请求繁忙,请稍后点击";
java实现接口防刷

文章插图
 
三、切面代码的实现
import com.south.wires.config.annotation.RateLimit;import com.south.wires.result.JsonResult;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.Signature;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.script.DefaultRedisScript;import org.springframework.data.redis.serializer.StringRedisSerializer;import org.springframework.stereotype.Component;import org.springframework.web.context.Request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import java.lang.reflect.Method;import java.util.Collections;@Slf4j@Aspect@Componentpublic class RateLimitAspect {@Autowiredprivate RedisTemplate redisTemplate;@Around("@annotation(com.xxx.xxx.config.annotation.RateLimit)")public JsonResult around(ProceedingJoinPoint joinPoint) throws Throwable {// 业务方法执行之前设置数据源...Boolean pass=doingSomthingBefore(joinPoint);Object result;if(pass){// 执行业务方法result =joinPoint.proceed();}else{// 业务方法执行之后清除数据源设置...result=doingSomthingAfter(joinPoint);//自定义的返回值的类型return JsonResult.success(result);private boolean doingSomthingBefore(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {// 接收到请求,记录请求内容ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String ip = request.getRemoteAddr();String uri = request.getRequestURI();// 记录下请求内容log.info("请求类型 :" + request.getMethod() + " " + "请求URL : " + request.getRequestURL());log.info("请求IP : " + request.getRemoteAddr());log.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());Method targetMethod=getTargetMethod(joinPoint);return selectLimit(ip, uri,targetMethod);private Method getTargetMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {//获取目标对象对应的字节码对象Class targetCls=joinPoint.getTarget().getClass();//获取方法签名信息从而获取方法名和参数类型Signature signature=joinPoint.getSignature();//将方法签名强转成MethodSignature类型,方便调用MethodSignature ms= (MethodSignature)signature;return targetCls.getDeclaredMethod(ms.getName(),ms.getParameterTypes());private String doingSomthingAfter(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {System.out.println("开始后");//获取方法上的自定义RateLimit注解RateLimit rateLimit=getTargetMethod(joinPoint).getAnnotation(RateLimit.class);return rateLimit.msg();private static final String SCRIPT = "local limit = tonumber(ARGV[1]);"// 限制次数+ "local expire_time = ARGV[2];"// 过期时间+ "local result = redis.call('setNX',KEYS[1],1);"// key不存在时设置value为1,返回1、否则返回0+ "if result == 1 then"// 返回值为1,key不存在此时需要设置过期时间+ " redis.call('expire',KEYS[1],expire_time);"// 设置过期时间+ " return 1; "// 返回1+ "else"// key存在+ " if tonumber(redis.call('GET', KEYS[1])) >= limit then"// 判断数目比对+ " return 0;"// 如果超出限制返回0+ " else" //+ " redis.call('incr', KEYS[1]);"// key自增+ " return 1 ;"// 返回1+ " end "// 结束+ "end";// 结束public Boolean selectLimit(String ip, String url,Method targetMethod) {String key = "custom:rate" + ip + ":" + url;StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();redisTemplate.setValueSerializer(stringRedisSerializer);redisTemplate.setKeySerializer(stringRedisSerializer);DefaultRedisScript defaultRedisScript = new DefaultRedisScript<>(SCRIPT);defaultRedisScript.setResultType(Boolean.class);Boolean execute = null;try {RateLimit rateLimit=targetMethod.getAnnotation(RateLimit.class);execute = (Boolean) redisTemplate.execute(defaultRedisScript, Collections.singletonList(key), rateLimit.number(),rateLimit.cycle());} catch (Exception ex) {ex.printStackTrace();if (!execute) {return false;return true;


推荐阅读