龙空技术网

java实现接口防刷

从事java的小白 3989

前言:

今天小伙伴们对“java登录接口”大概比较注意,大家都想要了解一些“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 "请求繁忙,请稍后点击";}

三、切面代码的实现

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 {    @Autowired    private 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;    }}

四、控制层添加相应的注解

@RateLimit@ResponseBody@RequestMapping("testRateLimit")public Object test2(){    System.out.println("执行检索");    return "请求成功";}

控制层代码执行

接口请求执行成功

接口请求失败

标签: #java登录接口