1.实现登录次数限定
CredentialsMatcher是shiro提供的用于加密密码和验证密码服务的接口,而HashedCredentialsMatcher正是CredentialsMatcher的一个实现类。
新写一个类继承HashedCredentialsMatcher,在重写doCredentialsMatch,判断如果验证密码次数超过5次,抛出异常。
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
private Cache<String, AtomicInteger> passwordRetryCache;
public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
passwordRetryCache = cacheManager.getCache("passwordRetryCache");
}
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
String username = (String) token.getPrincipal();
AtomicInteger retryCount = passwordRetryCache.get(username);
// 查看缓存中的尝试次数
if (retryCount == null) {
retryCount = new AtomicInteger(0);
passwordRetryCache.put(username, retryCount);
}
// 超过五次,抛异常
if (retryCount.incrementAndGet() > 5) {
throw new ExcessiveAttemptsException();
}
// 判断登录
boolean matches = super.doCredentialsMatch(token, info);
if (matches) {
passwordRetryCache.remove(username);
}
return matches;
}
}
在shiroconfig中,原本HashedCredentialsMatcher的实现类是HashedCredentialsMatcher,现在换成我们新写的RetryLimitHashedCredentialsMatcher
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new RetryLimitHashedCredentialsMatcher(ehCacheManager());
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
}
在登录中加上对这个异常的处理
else if (ExcessiveAttemptsException.class.getName().equals(exception)) {
System.out.println("ExcessiveAttemptsException -- > 登录失败次数过多:");
msg = "ExcessiveAttemptsException -- > 登录失败次数过多:";
}
连续登录五次之后的效果:
2.thymeleaf中使用shiro标签
导入包
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
https://github.com/theborakompanioni/thymeleaf-extras-shiro
这里有个问题:
我为了开启thymeleaf的弱语法检测,用的不是springboot默认的thymeleaf版本,而是指定了thymefeaf版本
<!--提高thymeleaf的版本,以支持thymeleaf的若语法检测-->
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
所以thymeleaf-extras-shiro的版本也要相应的升级。
thymeleaf是低版本的话,可以用1.0.2之类的hymeleaf-extras-shiro