最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Shiro+Redis實(shí)現(xiàn)登錄次數(shù)凍結(jié)的示例

 更新時(shí)間:2020年12月17日 11:48:10   作者:一個(gè)JavaBean  
這篇文章主要介紹了Shiro+Redis實(shí)現(xiàn)登錄次數(shù)凍結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

概述

假設(shè)我們需要有這樣一個(gè)場(chǎng)景:如果用戶連續(xù)輸錯(cuò)5次密碼,那可能說(shuō)明有人在搞事情,所以需要暫時(shí)凍結(jié)該賬戶的登錄功能

關(guān)于Shiro整合JWT,可以看這里:Springboot實(shí)現(xiàn)Shiro+JWT認(rèn)證

假設(shè)我們的項(xiàng)目中用到了shiro,因?yàn)镾hiro是建立在完善的接口驅(qū)動(dòng)設(shè)計(jì)和面向?qū)ο笤瓌t之上的,支持各種自定義行為,所以我們可以結(jié)合Shiro框架的認(rèn)證模塊和redis來(lái)實(shí)現(xiàn)這個(gè)功能。

思路

我們大體的思路如下:

image-20200225151338221

  • 用戶登錄
  • Shiro去Redis檢查賬戶的登錄錯(cuò)誤次數(shù)是否超過(guò)規(guī)定范圍(超過(guò)了就是所謂的凍結(jié))
  • Shiro進(jìn)行密碼比對(duì)
  • 如果登錄失敗,則去Redis里記錄:登錄錯(cuò)誤次數(shù)+1
  • 如果密碼正確,則登錄成功,刪除Redis里的登錄錯(cuò)誤記錄

前期準(zhǔn)備

除了需要用到Shiro以外,我們也需要用到Redis,這里需要先配置好RedisTemplate,(由于這個(gè)不是重點(diǎn),我就把代碼和配置方法貼在文章的最后了),另外,在Controller層,登錄接口的異常處理除了之前的登錄錯(cuò)誤,還需要新增一個(gè)賬戶凍結(jié)類的異常,代碼如下:

 @PostMapping(value = "/login")
 public AccountVO login(String userName, String password){
  
  //嘗試登錄
  Subject subject = SecurityUtils.getSubject();
  try {
   //通過(guò)shiro提供的安全接口來(lái)進(jìn)行認(rèn)證
   subject.login(new UsernamePasswordToken(userName, password));
  } catch (ExcessiveAttemptsException e1) {
   //新增一個(gè)賬戶鎖定類錯(cuò)誤
   throw new AccountLockedException();
  } catch (Exception e) {
   //其他的錯(cuò)誤判定
   throw new LoginFailed();
  }
  //聚合登錄信息
  AccountVO account = accountService.getAccountByUserName(userName);
  //返回正確登錄的結(jié)果
  return account;
 }

自定義Shiro認(rèn)證管理器

HashedCredentialsMatcher

當(dāng)你在上面的Controller層調(diào)用subject.login方法后,會(huì)進(jìn)入到自定義的Realm里去,然后慢慢進(jìn)入到Shiro當(dāng)前的Security Manager里定義的HashedCredentialsMatcher認(rèn)證管理器的doCredentialsMatch方法,進(jìn)行密碼匹配,原版代碼如下:

 /**
  * 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);
 }

可以發(fā)現(xiàn),原版的邏輯很簡(jiǎn)單,就做了兩件事,獲取密碼,比對(duì)密碼。

由于我們需要聯(lián)動(dòng)Redis,在每次登錄前都做一次凍結(jié)檢查,每次遇到登錄失敗之后還需要實(shí)現(xiàn)對(duì)redis的寫操作,所以現(xiàn)在需要重寫一個(gè)認(rèn)證管理器去配置到Security Manager里。

CustomMatcher

我們自定義一個(gè)CustomMatcher,這個(gè)類繼承了HashedCredentialsMatcher,唯獨(dú)重寫了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 {

	//這個(gè)是redis里的key的統(tǒng)一前綴
 private static final String PREFIX = "USER_LOGIN_FAIL:";

 @Autowired
 RedisStringService redisUtils;

 @Override
 public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

  //檢查本賬號(hào)是否被凍結(jié)

  //先獲取用戶的登錄名字 
  UsernamePasswordToken myToken = (UsernamePasswordToken) token;

  String userName = myToken.getUsername();

  //初始化錯(cuò)誤登錄次數(shù)
  Integer errorNum = 0;

  //從數(shù)據(jù)庫(kù)里獲取錯(cuò)誤次數(shù)
  String errorTimes = (String)redisUtils.get(PREFIX+userName);

  if(errorTimes!=null && errorTimes.trim().length()>0)
  {
   //如果得到的字符串不為空不為空
   errorNum = Integer.parseInt(errorTimes);
  }

  //如果用戶錯(cuò)誤登錄次數(shù)超過(guò)十次
  if (errorNum >= 10) {
   //拋出賬號(hào)鎖定異常類
   throw new ExcessiveAttemptsException();
  }

  //先按照父類的規(guī)則來(lái)比對(duì)密碼
  boolean matched = super.doCredentialsMatch(token, info);

  if(matched)
  {
   //清空錯(cuò)誤次數(shù)
   redisUtils.remove(PREFIX+userName);
  }
  else{
   //添加一次錯(cuò)誤次數(shù) 秒為單位
   redisUtils.set(PREFIX+userName,String.valueOf(++errorNum),60*30L);
  }

  return matched;
 }
}

首先,我們從AuthenticationToken里面拿到之前存入的用戶的登錄信息,這個(gè)對(duì)象其實(shí)就是你在Controller層

subject.login(new UsernamePasswordToken(userName, password));

這一步里面你實(shí)例化的對(duì)象

然后,通過(guò)用戶的登錄名加上固定前綴(為了防止防止userName和其他主鍵沖突)去Redis里獲取到錯(cuò)誤次數(shù)。判斷賬戶是否被凍結(jié)的邏輯其實(shí)就是看當(dāng)前用戶的錯(cuò)誤登錄次數(shù)是否超過(guò)某個(gè)規(guī)定值,這里我們定為5次。

接下來(lái),說(shuō)明用戶沒有被凍結(jié),可以執(zhí)行登錄操作,所以我們就直接調(diào)用父類的驗(yàn)證方法來(lái)進(jìn)行密碼比對(duì)(就是之前提到的那三行代碼),得到密碼的比對(duì)結(jié)果

如果比對(duì)一致,那么就成功登錄,返回true即可,也可以選擇一旦登錄成功,就消除所有錯(cuò)誤次數(shù)記錄,上面的代碼就是這樣做的。

如果對(duì)比結(jié)果不一樣,那就再添加一次錯(cuò)誤記錄,然后返回false

測(cè)試

第一次登錄:頁(yè)面結(jié)果:

image-20200225153743161

Redis中:

image-20200225154251776

然后連續(xù)錯(cuò)誤10次:

頁(yè)面結(jié)果:

image-20200225154434428

Redis中:

image-20200225154406113

然后等待了半小時(shí)之后(其實(shí)我調(diào)成了5分鐘)

再次嘗試錯(cuò)誤密碼登錄:

image-20200225153743161

再次報(bào)錯(cuò),此時(shí)Redis里由于之前的記錄到期了,自動(dòng)銷毀了,所以再次觸發(fā)錯(cuò)誤又會(huì)添加一次錯(cuò)誤記錄

image-20200225154645626

現(xiàn)在嘗試一次正確登錄:

image-20200225154735645

成功登錄

查看Redis:

image-20200225154807011

🎉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)
 {
	//我就用的默認(rèn)的序列化處理器
  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

一個(gè)只能用來(lái)處理Value是String的工具類,就是我在CustomMatcher里Autowired的這個(gè)類

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緩存(不設(shè)置expire存活時(shí)間)
  * @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緩存(設(shè)置expire存活時(shí)間)
  * @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緩存中是否有對(duì)應(yīng)的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根據(jù)key刪除對(duì)應(yīng)的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根據(jù)keys批量刪除對(duì)應(yīng)的value
  * @param keys
  * @return
  */
 public void remove(final String... keys){
  for(String key : keys){
   remove(key);
  }
 }
}

到此這篇關(guān)于Shiro+Redis實(shí)現(xiàn)登錄次數(shù)凍結(jié)的文章就介紹到這了,更多相關(guān)Shiro+Redis登錄凍結(jié)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 教新手使用java如何對(duì)一個(gè)大的文本文件內(nèi)容進(jìn)行去重

    教新手使用java如何對(duì)一個(gè)大的文本文件內(nèi)容進(jìn)行去重

    用HashSet對(duì)內(nèi)容去重這個(gè)過(guò)程jvm會(huì)內(nèi)存溢出,只能首先將這個(gè)大文件中的內(nèi)容讀取出來(lái),對(duì)每行String的hashCode取模取正整數(shù),可用取模結(jié)果作為文件名,將相同模數(shù)的行寫入同一個(gè)文件,再單獨(dú)對(duì)每個(gè)小文件進(jìn)行去重,最后再合并
    2021-06-06
  • java實(shí)現(xiàn)dijkstra最短路徑尋路算法

    java實(shí)現(xiàn)dijkstra最短路徑尋路算法

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)dijkstra最短路徑尋路算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • Java實(shí)現(xiàn)圖片轉(zhuǎn)base64完整代碼示例

    Java實(shí)現(xiàn)圖片轉(zhuǎn)base64完整代碼示例

    這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)圖片轉(zhuǎn)base64的相關(guān)資料,Base64是網(wǎng)絡(luò)上最常見的用于傳輸8Bit字節(jié)碼的編碼方式之一,Base64就是一種基于64個(gè)可打印字符來(lái)表示二進(jìn)制數(shù)據(jù)的方法,需要的朋友可以參考下
    2023-12-12
  • Spring security權(quán)限配置與使用大全

    Spring security權(quán)限配置與使用大全

    Spring Security 本質(zhì)上是借助一系列的 Servlet Filter來(lái)提供各種安全性功能,但這并不需要我們手動(dòng)去添加或者創(chuàng)建多個(gè)Filter,本文重點(diǎn)給大家介紹spring-security的配置與使用及實(shí)現(xiàn)方式,感興趣的朋友一起看看吧
    2021-09-09
  • SpringBoot設(shè)置編碼UTF-8的兩種方法

    SpringBoot設(shè)置編碼UTF-8的兩種方法

    本文通過(guò)兩種方式給大家介紹SpringBoot 設(shè)置編碼UTF-8 ,每種方式通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-11-11
  • Spring Cloud Gateway去掉url前綴

    Spring Cloud Gateway去掉url前綴

    這篇文章主要介紹了Spring Cloud Gateway去掉url前綴的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • 解決springboot啟動(dòng)Logback報(bào)錯(cuò)ERROR in ch.qos.logback.classic.joran.action.ContextNameAction - Failed to rena

    解決springboot啟動(dòng)Logback報(bào)錯(cuò)ERROR in ch.qos.logback.cla

    這篇文章主要介紹了解決springboot啟動(dòng)Logback報(bào)錯(cuò)ERROR in ch.qos.logback.classic.joran.action.ContextNameAction - Failed to rena問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • Java異常簡(jiǎn)介和架構(gòu)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    Java異常簡(jiǎn)介和架構(gòu)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要分享了Java異常簡(jiǎn)介和架構(gòu),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • SpringBoot實(shí)現(xiàn)點(diǎn)餐系統(tǒng)的登錄與退出功能流程詳解

    SpringBoot實(shí)現(xiàn)點(diǎn)餐系統(tǒng)的登錄與退出功能流程詳解

    結(jié)束了Springboot+MyBatisPlus也是開始了項(xiàng)目之旅,將從后端的角度出發(fā)來(lái)整理這個(gè)項(xiàng)目中重點(diǎn)業(yè)務(wù)功能的梳理與實(shí)現(xiàn)
    2022-10-10
  • 理解Java中的靜態(tài)綁定和動(dòng)態(tài)綁定

    理解Java中的靜態(tài)綁定和動(dòng)態(tài)綁定

    這篇文章主要幫助大家理解Java中的靜態(tài)綁定和動(dòng)態(tài)綁定,在Java中存在兩種綁定方式,一種為靜態(tài)綁定,另一種就是動(dòng)態(tài)綁定,亦稱為后期綁定,感興趣的小伙伴們可以參考一下
    2016-02-02

最新評(píng)論

宜春市| 叶城县| 环江| 岑溪市| 杭州市| 台南市| 绥德县| 黄山市| 阳西县| 蕲春县| 木兰县| 沽源县| 永修县| 都安| 博湖县| 黑水县| 绵竹市| 峨眉山市| 轮台县| 长葛市| 江口县| 霍邱县| 门头沟区| 伊宁市| 那坡县| 九江市| 锡林郭勒盟| 密云县| 贵定县| 许昌县| 新晃| 靖西县| 柏乡县| 柳州市| 明溪县| 仁怀市| 休宁县| 鄂伦春自治旗| 内丘县| 栾城县| 吉安市|