Shiro+Redis实现登录次数冻结的示例

概述

假设我们需要有这样一个场景:如果用户连续输错5次密码,那可能说明有人在搞事情,所以需要暂时冻结该账户的登录功能

关于shiro整合jwt,可以看这里:springboot实现shiro+jwt认证

假设我们的项目中用到了shiro,因为shiro是建立在完善的接口驱动设计和面向对象原则之上的,支持各种自定义行为,所以我们可以结合shiro框架的认证模块和redis来实现这个功能。

思路

我们大体的思路如下:

  • 用户登录
  • shiro去redis检查账户的登录错误次数是否超过规定范围(超过了就是所谓的冻结)
  • shiro进行密码比对
  • 如果登录失败,则去redis里记录:登录错误次数+1
  • 如果密码正确,则登录成功,删除redis里的登录错误记录

前期准备

除了需要用到shiro以外,我们也需要用到redis,这里需要先配置好redistemplate,(由于这个不是重点,我就把代码和配置方法贴在文章的最后了),另外,在controller层,登录接口的异常处理除了之前的登录错误,还需要新增一个账户冻结类的异常,代码如下:

 @postmapping(value = "/login")
 public accountvo login(string username, string password){
  
  //尝试登录
  subject subject = securityutils.getsubject();
  try {
   //通过shiro提供的安全接口来进行认证
   subject.login(new usernamepasswordtoken(username, password));
  } catch (excessiveattemptsexception e1) {
   //新增一个账户锁定类错误
   throw new accountlockedexception();
  } catch (exception e) {
   //其他的错误判定
   throw new loginfailed();
  }
  //聚合登录信息
  accountvo account = accountservice.getaccountbyusername(username);
  //返回正确登录的结果
  return account;
 }

自定义shiro认证管理器

hashedcredentialsmatcher

当你在上面的controller层调用subject.login方法后,会进入到自定义的realm里去,然后慢慢进入到shiro当前的security manager里定义的hashedcredentialsmatcher认证管理器的docredentialsmatch方法,进行密码匹配,原版代码如下:

 /**
  * this implementation first hashes the {@code token}'s credentials, potentially using a
  * {@code salt} if the {@code info} argument is a
  * {@link org.apache.shiro.authc.saltedauthenticationinfo saltedauthenticationinfo}. it then compares the hash
  * against the {@code authenticationinfo}'s
  * {@link #getcredentials(org.apache.shiro.authc.authenticationinfo) already-hashed credentials}. this method
  * returns {@code true} if those two values are {@link #equals(object, object) equal}, {@code false} otherwise.
  *
  * @param token the {@code authenticationtoken} submitted during the authentication attempt.
  * @param info the {@code authenticationinfo} stored in the system matching the token principal
  * @return {@code true} if the provided token credentials hash match to the stored account credentials hash,
  *   {@code false} otherwise
  * @since 1.1
  */
 @override
 public boolean docredentialsmatch(authenticationtoken token, authenticationinfo info) {
  object tokenhashedcredentials = hashprovidedcredentials(token, info);
  object accountcredentials = getcredentials(info);
  return equals(tokenhashedcredentials, accountcredentials);
 }

可以发现,原版的逻辑很简单,就做了两件事,获取密码,比对密码。

由于我们需要联动redis,在每次登录前都做一次冻结检查,每次遇到登录失败之后还需要实现对redis的写操作,所以现在需要重写一个认证管理器去配置到security manager里。

custommatcher

我们自定义一个custommatcher,这个类继承了hashedcredentialsmatcher,唯独重写了docredentialsmatch方法,在这里面加入了我们自己的逻辑,代码如下:

import com.imlehr.internship.redis.redisstringservice;
import org.apache.shiro.authc.authenticationinfo;
import org.apache.shiro.authc.authenticationtoken;
import org.apache.shiro.authc.excessiveattemptsexception;
import org.apache.shiro.authc.usernamepasswordtoken;
import org.apache.shiro.authc.credential.hashedcredentialsmatcher;
import org.springframework.beans.factory.annotation.autowired;

/**
 * @author lehr
 * @create: 2020-02-25
 */
public class custommatcher extends hashedcredentialsmatcher {

	//这个是redis里的key的统一前缀
 private static final string prefix = "user_login_fail:";

 @autowired
 redisstringservice redisutils;

 @override
 public boolean docredentialsmatch(authenticationtoken token, authenticationinfo info) {

  //检查本账号是否被冻结

  //先获取用户的登录名字 
  usernamepasswordtoken mytoken = (usernamepasswordtoken) token;

  string username = mytoken.getusername();

  //初始化错误登录次数
  integer errornum = 0;

  //从数据库里获取错误次数
  string errortimes = (string)redisutils.get(prefix+username);

  if(errortimes!=null && errortimes.trim().length()>0)
  {
   //如果得到的字符串不为空不为空
   errornum = integer.parseint(errortimes);
  }

  //如果用户错误登录次数超过十次
  if (errornum >= 10) {
   //抛出账号锁定异常类
   throw new excessiveattemptsexception();
  }

  //先按照父类的规则来比对密码
  boolean matched = super.docredentialsmatch(token, info);

  if(matched)
  {
   //清空错误次数
   redisutils.remove(prefix+username);
  }
  else{
   //添加一次错误次数 秒为单位
   redisutils.set(prefix+username,string.valueof(++errornum),60*30l);
  }

  return matched;
 }
}

首先,我们从authenticationtoken里面拿到之前存入的用户的登录信息,这个对象其实就是你在controller层

subject.login(new usernamepasswordtoken(username, password));

这一步里面你实例化的对象

然后,通过用户的登录名加上固定前缀(为了防止防止username和其他主键冲突)去redis里获取到错误次数。判断账户是否被冻结的逻辑其实就是看当前用户的错误登录次数是否超过某个规定值,这里我们定为5次。

接下来,说明用户没有被冻结,可以执行登录操作,所以我们就直接调用父类的验证方法来进行密码比对(就是之前提到的那三行代码),得到密码的比对结果

如果比对一致,那么就成功登录,返回true即可,也可以选择一旦登录成功,就消除所有错误次数记录,上面的代码就是这样做的。

如果对比结果不一样,那就再添加一次错误记录,然后返回false

测试

第一次登录:页面结果:

redis中:

然后连续错误10次:

页面结果:

redis中:

然后等待了半小时之后(其实我调成了5分钟)

再次尝试错误密码登录:

再次报错,此时redis里由于之前的记录到期了,自动销毁了,所以再次触发错误又会添加一次错误记录

现在尝试一次正确登录:

成功登录

查看redis:

done!

附redistemplate代码

配置类

import org.springframework.boot.autoconfigure.condition.conditionalonmissingbean;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.serializer.jdkserializationredisserializer;
import org.springframework.data.redis.serializer.stringredisserializer;

@configuration
public class redisconfig {

 @bean
 public redistemplate<string, object> redistemplate(redisconnectionfactory redisconnectionfactory)
 {
	//我就用的默认的序列化处理器
  stringredisserializer stringredisserializer = new stringredisserializer();
  jdkserializationredisserializer ser = new jdkserializationredisserializer();

  redistemplate<string, object> template = new redistemplate<string, object>();
  template.setconnectionfactory(redisconnectionfactory);

  template.setkeyserializer(stringredisserializer);
  template.setvalueserializer(ser);
  return template;
 }

 @bean
 public redisstringservice mystringredistemplate()
 {
  return new redisstringservice();
 }
}

工具类redisstringservice

一个只能用来处理value是string的工具类,就是我在custommatcher里autowired的这个类

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.core.valueoperations;
import org.springframework.stereotype.service;

import java.util.concurrent.timeunit;

public class redisstringservice {

 @autowired
 protected stringredistemplate redistemplate;

 /**
  * 写入redis缓存(不设置expire存活时间)
  * @param key
  * @param value
  * @return
  */
 public boolean set(final string key, string value){
  boolean result = false;
  try {
   valueoperations operations = redistemplate.opsforvalue();
   operations.set(key, value);
   result = true;
  } catch (exception e) {
   e.getmessage();
  }
  return result;
 }

 /**
  * 写入redis缓存(设置expire存活时间)
  * @param key
  * @param value
  * @param expire
  * @return
  */
 public boolean set(final string key, string value, long expire){
  boolean result = false;
  try {
   valueoperations operations = redistemplate.opsforvalue();
   operations.set(key, value);
   redistemplate.expire(key, expire, timeunit.seconds);
   result = true;
  } catch (exception e) {
   e.getmessage();
  }
  return result;
 }


 /**
  * 读取redis缓存
  * @param key
  * @return
  */
 public object get(final string key){
  object result = null;
  try {
   valueoperations operations = redistemplate.opsforvalue();
   result = operations.get(key);
  } catch (exception e) {
   e.getmessage();
  }
  return result;
 }

 /**
  * 判断redis缓存中是否有对应的key
  * @param key
  * @return
  */
 public boolean exists(final string key){
  boolean result = false;
  try {
   result = redistemplate.haskey(key);
  } catch (exception e) {
   e.getmessage();
  }
  return result;
 }

 /**
  * redis根据key删除对应的value
  * @param key
  * @return
  */
 public boolean remove(final string key){
  boolean result = false;
  try {
   if(exists(key)){
    redistemplate.delete(key);
   }
   result = true;
  } catch (exception e) {
   e.getmessage();
  }
  return result;
 }

 /**
  * redis根据keys批量删除对应的value
  * @param keys
  * @return
  */
 public void remove(final string... keys){
  for(string key : keys){
   remove(key);
  }
 }
}

到此这篇关于shiro+redis实现登录次数冻结的文章就介绍到这了,更多相关shiro+redis登录冻结内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐