redis 实现登陆次数限制
title: redis-login-limitation
基本思路
比如希望达到的要求是这样: 在 1min 内登陆异常次数达到5次, 锁定该用户 1h
那么登陆请求的参数中, 会有一个参数唯一标识一个 user, 比如 邮箱/手机号/userName
用这个参数作为key存入redis, 对应的value为登陆错误的次数, string 类型, 并设置过期时间为 1min. 当获取到的 value == "4" , 说明当前请求为第 5 次登陆异常, 锁定.
所谓的锁定, 就是将对应的value设置为某个标识符, 比如"lock", 并设置过期时间为 1h
核心代码
定义一个注解, 用来标识需要登陆次数校验的方法
package io.github.xiaoyureed.redispractice.anno;
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLimit {
/**
* 标识参数名, 必须是请求参数中的一个
*/
String identifier();
/**
* 在多长时间内监控, 如希望在 60s 内尝试
* 次数限制为5次, 那么 watch=60; unit: s
*/
long watch();
/**
* 锁定时长, unit: s
*/
long lock();
/**
* 错误的尝试次数
*/
int times();
}
编写切面, 在目标方法前后进行校验, 处理...
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);// 貌似可以直接在方法参数中注入 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);
}
}
这样使用:
package io.github.xiaoyureed.redispractice.web;
@RestController
public class SessionResources {
@Autowired
private SessionService sessionService;
/**
* 1 min 之内尝试超过5次, 锁定 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
redis 实现登陆次数限制的更多相关文章
- 【BASIS系列】SAP 中查看account登陆次数及时间的情况
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[BASIS系列]SAP 中查看account登 ...
- Redis解决“重试次数”场景的实现思路
很多地方都要用到重试次数限制,不然就会被暴力破解.比如登录密码. 下面不是完整代码,只是伪代码,提供一个思路. 第一种(先声明,这样写有个bug) import java.text.MessageFo ...
- 【Redis使用系列】redis设置登陆密码
找到安装redis的配置文件,找到redis.comf文件找到#requirepass foobared 新建一行 requirepass xxxx 你的密码 ,然后重启.再登录的时候可以登录,但是 ...
- shiro 错误登陆次数限制
第一步:在spring-shiro.xml 中配置缓存管理器和认证匹配器 <!-- 缓存管理器 使用Ehcache实现 --><bean id="cacheManager& ...
- 帝国empirecms后台登陆次数限制修改
打开文件:\e\config\config.php, 找到 'loginnum'=>5, 把5改为自己想要的数字即可
- Servlet学习(三)——实例:用户登录并记录登陆次数
1.前提:在Mysql数据库下建立数据库web13,在web13下创建一张表user,插入几条数据如下: 2.创建HTML文件,命名为login,作为登录界面(以post方式提交) <!DOCT ...
- Redis & Python/Django 简单用户登陆
一.Redis key相关操作: 1.del key [key..] 删除一个或多个key,如果不存在则忽略 2.keys pattern keys模式匹配,符合glob风格通配符,glob风格的通配 ...
- Redis+Django(Session,Cookie)的用户系统
一.Django authentication django authentication提供了一个便利的user api接口,无论在py中 request.user,参见Request and re ...
- Redis+Django(Session,Cookie、Cache)的用户系统
转自 http://www.cnblogs.com/BeginMan/p/3890761.html 一.Django authentication django authentication 提供了一 ...
随机推荐
- NetworkX系列教程(10)-算法之二:最小/大生成树问题
小书匠 Graph 图论 重头戏部分来了,写到这里我感觉得仔细认真点了,可能在NetworkX中,实现某些算法就一句话的事,但是这个算法是做什么的,用在什么地方,原理是怎么样的,不清除,所以,我决定 ...
- D-【乐】k进制数(同余)
题目 https://ac.nowcoder.com/acm/contest/907/D 做法 \((x)_k\)定义编号,如果\(a+b\)加到一起能进一位,\(a+b\rightarrow 1+( ...
- Hadoop(4)MapReduce 任务的推测(speculative)执行
Straggle(掉队者)是指那些跑的很慢但最终会成功完成的任务.一个掉队的Map任务会阻止Reduce任务开始执行. Hadoop不能自动纠正掉队任务,但是可以识别那些跑的比较慢的任务,然后它会产生 ...
- MangoDB在C#中的使用
http://blog.sina.com.cn/s/blog_927f3c2401011937.html 图形工具 http://api.mongodb.org/csharp/current/html ...
- java四种对象引用类型
java四种对象引用类型 对象的强.软.弱和虚引用 在JDK 1.2以前的版本中,若一个对象不被任何变量引用,那么程序就无法再使用这个对象.也就是说,只有对象处于可触及(reachable)状态,程序 ...
- LuaJIT 之 FFI
1. FFI 教程 原文: FFI Tutorial 相关链接:OpenResty 最佳实践之 FFI 加载 FFI 库 FFI 库时默认编译进 LuaJIT 中的,但是不会默认加载或初始化.因此,当 ...
- ML_Homework_Porject_1_KMeans
第一次机器学习的作业完成了,按照先前做实作的习惯来写一下总结和思考. 作业要求:对COIL20,Yale_32x32,data_batch_1(Cifar)三个数据集,分别运用KMeans对其中的图片 ...
- IDEA在线和离线安装lombok
1. IDEA在线安装: 点击安装,电子reset 如果以上方式安装失败, 去以下任意网站下载对应版本插件安装: http://plugins.jetbrains.com/plugin/6317-l ...
- OpenTK学习笔记(2)-工作窗口的三种方法创建方法(winfrom窗体控件形式创建)
参考资料: https://social.msdn.microsoft.com/Forums/zh-TW/1b781685-c670-4338-953d-1957a8f24a66/opentkglco ...
- python-pptx add_image_picture