1.场景
登录或注册接口中,使用短信验证码场景时,遇到恶意调用短信接口,一毫秒多次调用,导致短信资源大幅度消耗。
2.排查
经排查发现,短信发送接口无限制,仅通过redis保留验证码发送信息。一个时间戳产生数次甚至十几次调用,多个线程同时访问redis后,取值相同,均通过验证前往调用短信接口。
3.解决方案
使用redis分布式锁,解决该问题。
相关代码如下:
3.1 redis锁实现
public class redislock { @autowired private redistemplate<string, string> redistemplate; private static final long nx = 1l; // 超时时间 public boolean trylock(string key, string value) { // 超时时间单位,这里发现,较新版本的redistemplate中,setifabsent方法时间单位为timeunit,并非大多帖子中表述的long类型 timeunit timeunit = timeunit.minutes; // 这里设置redis锁超时时间为1分钟 boolean result = redistemplate.opsforvalue().setifabsent(key, value, nx, timeunit); return result != null && result; } // unlock方法未测试,请测试后再使用 public void unlock(string key, string value) { string script = "if redis.call('get', keys[1]) == argv[1] then " + "return redis.call('del', keys[1]) " + "else " + "return 0 " + "end"; redistemplate.execute((rediscallback<boolean>) connection -> { object nativeconnection = connection.getnativeconnection(); if (nativeconnection instanceof jedis) { return ((jedis) nativeconnection).eval(script, collections.singletonlist(key), collections.singletonlist(value)).equals(1l); } else if (nativeconnection instanceof redisclusterconnection) { return ((redisclusterconnection) nativeconnection).eval(script.getbytes(), returntype.integer, 1, key.getbytes(), value.getbytes()).equals(1l); } return false; }); } }
3.2 方法调用
public boolean getverfitycode(string mobile) { string smscode = sharecodeutils.smscode(); // redis锁参数 string lockkey = "sms_lock_" + mobile; string lockvalue = uuid.randomuuid().tostring(); boolean send = false; try { if (redislock.trylock(lockkey, lockvalue)) { // 获取锁成功,触发短信验证码功能(具体逻辑,此处因原登录逻辑需要redis支持,故保留) string s = redisutils.get(rediskeys.verfity_code + mobile); if (s != null) { // 判断验证码是否过期 throw new serviceexception("验证码未过期,请勿重复获取"); } // 发送验证码 send = smsbaoutil.sendsms(mobile, smscode); if (send) { // reids 中不存在 此电话对应验证码证明已经过了 vercodetm 秒,则可以重新生成 redisutils.set(rediskeys.verfity_code + mobile, smscode, vercodetm); } } } catch (exception e) { send = false; } // 很多帖子这里会增加finally解锁逻辑,这里为了保证1分钟内不会再触发短信恶意调用,取消解锁逻辑,由redis超时销毁后,自动解锁。 return send; }
到此这篇关于redis防止短信恶意调用的实现的文章就介绍到这了,更多相关redis防止短信恶意调用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论