redis 实现登陆次数限制
程序员文章站
2023-11-13 23:03:10
title: redis login limitation
title: redis-login-limitation
利用 redis 实现登陆次数限制, 注解 + aop, 核心代码很简单.
基本思路
比如希望达到的要求是这样: 在 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