A detailed explanation of redis's implementation of login frequency limit

  • 2020-06-23 02:16:03
  • OfStack

title: redis-login-limitation

Using redis to achieve the limit of login times, annotations + aop, the core code is very simple.

The basic idea

For example, the desired requirement is to log in five times within 1min and lock that user 1h

Then, among the parameters of the login request, there will be one parameter that only identifies one user, such as email/phone number /userName

This parameter is used to store redis as key, and the corresponding value is the number of login errors, type string, and the expiration time is set to 1min. When value == "4" is obtained, it indicates that the current request is the 5th login exception and is locked.

Locking means setting the corresponding value to an identifier, such as "lock", and setting the expiration time to 1h

The core code

Defines a comment to identify a method that requires login count verification


package io.github.xiaoyureed.redispractice.anno;
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLimit {
  /**
   *  Identification parameter name ,  Must be in the request parameter 1 a 
   */
  String identifier();
  /**
   *  How long to monitor ,  If hope to  60s  In the attempt 
   *  The frequency limit is 5 time ,  then  watch=60; unit: s
   */
  long watch();
  /**
   *  The lock time , unit: s
   */
  long lock();
  /**
   *  Wrong attempts 
   */
  int times();
}

Write sections, validate before and after the target method, process...


package io.github.xiaoyureed.redispractice.aop;
@Component
@Aspect
// Ensure that current advice is outer compared with ControllerAOP
// so we can handling login limitation Exception in this aop advice.
//@Order(9)
@Slf4j
public class RedisLimitAOP {
  @Autowired
  private StringRedisTemplate stringRedisTemplate;
  @Around("@annotation(io.github.xiaoyureed.redispractice.anno.RedisLimit)")
  public Object handleLimit(ProceedingJoinPoint joinPoint) {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    final Method   method     = methodSignature.getMethod();
    final RedisLimit redisLimitAnno = method.getAnnotation(RedisLimit.class);//  Looks like it can be injected directly into method parameters  todo
    final String identifier = redisLimitAnno.identifier();
    final long  watch   = redisLimitAnno.watch();
    final int  times   = redisLimitAnno.times();
    final long  lock    = redisLimitAnno.lock();
    // final ServletRequestAttributes att       = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    // final HttpServletRequest    request     = att.getRequest();
    // final String          identifierValue = request.getParameter(identifier);
    String identifierValue = null;
    try {
      final Object arg      = joinPoint.getArgs()[0];
      final Field declaredField = arg.getClass().getDeclaredField(identifier);
      declaredField.setAccessible(true);
      identifierValue = (String) declaredField.get(arg);
    } catch (NoSuchFieldException e) {
      log.error(">>> invalid identifier [{}], cannot find this field in request params", identifier);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    if (StringUtils.isBlank(identifierValue)) {
      log.error(">>> the value of RedisLimit.identifier cannot be blank, invalid identifier: {}", identifier);
    }
    // check User locked
    final ValueOperations<String, String> ssOps = stringRedisTemplate.opsForValue();
    final String             flag = ssOps.get(identifierValue);
    if (flag != null && "lock".contentEquals(flag)) {
      final BaseResp result = new BaseResp();
      result.setErrMsg("user locked");
      result.setCode("1");
      return new ResponseEntity<>(result, HttpStatus.OK);
    }
    ResponseEntity result;
    try {
      result = (ResponseEntity) joinPoint.proceed();
    } catch (Throwable e) {
      result = handleLoginException(e, identifierValue, watch, times, lock);
    }
    return result;
  }
  private ResponseEntity handleLoginException(Throwable e, String identifierValue, long watch, int times, long lock) {
    final BaseResp result = new BaseResp();
    result.setCode("1");
    if (e instanceof LoginException) {
      log.info(">>> handle login exception...");
      final ValueOperations<String, String> ssOps = stringRedisTemplate.opsForValue();
      Boolean                exist = stringRedisTemplate.hasKey(identifierValue);
      // key doesn't exist, so it is the first login failure
      if (exist == null || !exist) {
        ssOps.set(identifierValue, "1", watch, TimeUnit.SECONDS);
        result.setErrMsg(e.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
      }
      String count = ssOps.get(identifierValue);
      // has been reached the limitation
      if (Integer.parseInt(count) + 1 == times) {
        log.info(">>> [{}] has been reached the limitation and will be locked for {}s", identifierValue, lock);
        ssOps.set(identifierValue, "lock", lock, TimeUnit.SECONDS);
        result.setErrMsg("user locked");
        return new ResponseEntity<>(result, HttpStatus.OK);
      }
      ssOps.increment(identifierValue);
      result.setErrMsg(e.getMessage() + "; you have try " + ssOps.get(identifierValue) + "times.");
    }
    log.error(">>> RedisLimitAOP cannot handle {}", e.getClass().getName());
    return new ResponseEntity<>(result, HttpStatus.OK);
  }
}

Use as follows:


package io.github.xiaoyureed.redispractice.web;
@RestController
public class SessionResources {
  @Autowired
  private SessionService sessionService;
  /**
   * 1 min  Internal attempt exceeds 5 time ,  lock  user 1h
   */
  @RedisLimit(identifier = "name", watch = 30, times = 5, lock = 10)
  @RequestMapping(value = "/session", method = RequestMethod.POST)
  public ResponseEntity<LoginResp> login(@Validated @RequestBody LoginReq req) {
    return new ResponseEntity<>(sessionService.login(req), HttpStatus.OK);
  }
}

references

https://github.com/xiaoyureed/redis-login-limitation

conclusion


Related articles: