讲完 Shiro 的加解密后,又来了新需求。那就是如何通过Shiro 来限制密码错误次数。为了讲解这个问题,我们先来看看Shiro的PasswordService/CredentialsMatcher。
PasswordService/CredentialsMatcher
Shiro提供了PasswordService及CredentialsMatcher用于提供加密密码及验证密码服务。
public interface PasswordService {
//输入明文密码得到密文密码
String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;
}
public interface CredentialsMatcher {
//匹配用户输入的token的凭证(未加密)与系统提供的凭证(已加密)
boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);
}
Shiro默认提供了PasswordService实现DefaultPasswordService;CredentialsMatcher实现PasswordMatcher及HashedCredentialsMatcher(更强大)。
DefaultPasswordService/PasswordMatcher
DefaultPasswordService配合PasswordMatcher实现简单的密码加密与验证服务
public class XttblogRealm extends AuthorizingRealm {
private PasswordService passwordService;
public void setPasswordService(PasswordService passwordService) {
this.passwordService = passwordService;
}
//省略doGetAuthorizationInfo,具体看代码
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return new SimpleAuthenticationInfo(
"xttblog",
passwordService.encryptPassword("123"),
getName());
}
}
为了方便,直接注入一个passwordService来加密密码,实际使用时需要在Service层使用passwordService加密密码并存到数据库。
配置shiro-passwordservice.ini内容如下:
[main] passwordService=org.apache.shiro.authc.credential.DefaultPasswordService hashService=org.apache.shiro.crypto.hash.DefaultHashService passwordService.hashService=$hashService hashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormat passwordService.hashFormat=$hashFormat hashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory passwordService.hashFormatFactory=$hashFormatFactory passwordMatcher=org.apache.shiro.authc.credential.PasswordMatcher passwordMatcher.passwordService=$passwordService myRealm=com.xttblog.hash.realm.XttblogRealm myRealm.passwordService=$passwordService myRealm.credentialsMatcher=$passwordMatcher securityManager.realms=$myRealm
- passwordService使用DefaultPasswordService,如果有必要也可以自定义;
- hashService定义散列密码使用的HashService,默认使用DefaultHashService(默认SHA-256算法);
- hashFormat用于对散列出的值进行格式化,默认使用Shiro1CryptFormat,另外提供了Base64Format和HexFormat,对于有salt的密码请自定义实现ParsableHashFormat然后把salt格式化到散列值中;
- hashFormatFactory用于根据散列值得到散列的密码和salt;因为如果使用如SHA算法,那么会生成一个salt,此salt需要保存到散列后的值中以便之后与传入的密码比较时使用;默认使用DefaultHashFormatFactory;
- passwordMatcher使用PasswordMatcher,其是一个CredentialsMatcher实现;
- 将credentialsMatcher赋值给myRealm,myRealm间接继承了AuthenticatingRealm,其在调用getAuthenticationInfo方法获取到AuthenticationInfo信息后,会使用credentialsMatcher来验证凭据是否匹配,如果不匹配将抛出IncorrectCredentialsException异常。
java 测试用例PasswordTest 代码如下:
package com.xttblog.hash;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.converters.AbstractConverter;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.junit.Test;
public class PasswordTest extends BaseTest {
@Test
public void testPasswordServiceWithMyRealm() {
login("classpath:shiro-passwordservice.ini", "taoge", "123");
}
@Test
public void testPasswordServiceWithJdbcRealm() {
login("classpath:shiro-jdbc-passwordservice.ini", "taoge", "123");
}
@Test
public void testGeneratePassword() {
String algorithmName = "md5";
String username = "liu";
String password = "123";
String salt1 = username;
String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
int hashIterations = 2;
SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);
String encodedPassword = hash.toHex();
System.out.println(salt2);
System.out.println(encodedPassword);
}
@Test
public void testHashedCredentialsMatcherWithMyRealm2() {
//使用testGeneratePassword生成的散列密码
login("classpath:shiro-hashedCredentialsMatcher.ini", "blog", "123");
}
@Test
public void testHashedCredentialsMatcherWithJdbcRealm() {
BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);
//使用testGeneratePassword生成的散列密码
login("classpath:shiro-jdbc-hashedCredentialsMatcher.ini", "blog", "123");
}
private class EnumConverter extends AbstractConverter {
@Override
protected String convertToString(final Object value) throws Throwable {
return ((Enum) value).name();
}
@Override
protected Object convertToType(final Class type, final Object value) throws Throwable {
return Enum.valueOf(type, value.toString());
}
@Override
protected Class getDefaultType() {
return null;
}
}
@Test(expected = ExcessiveAttemptsException.class)
public void testRetryLimitHashedCredentialsMatcherWithMyRealm() {
for(int i = 1; i <= 5; i++) {
try {
login("classpath:shiro-retryLimitHashedCredentialsMatcher.ini", "blog", "234");
} catch (Exception e) {/*ignore*/}
}
login("classpath:shiro-retryLimitHashedCredentialsMatcher.ini", "blog", "234");
}
}
上面方式的缺点是:salt保存在散列值中;没有实现如密码重试次数限制。
HashedCredentialsMatcher实现密码验证服务
Shiro提供了CredentialsMatcher的散列实现HashedCredentialsMatcher,和之前的PasswordMatcher不同的是,它只用于密码验证,且可以提供自己的盐,而不是随机生成盐,且生成密码散列值的算法需要自己写,因为能提供自己的盐。
生成密码散列值
此处我们使用MD5算法,“密码+盐(用户名+随机数)”的方式生成散列值:
String algorithmName = "md5"; String username = "codedq"; String password = "123"; String salt1 = username; String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex(); int hashIterations = 2; SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations); String encodedPassword = hash.toHex();
如果要写用户模块,需要在新增用户/重置密码时使用如上算法保存密码,将生成的密码及salt2存入数据库(因为我们的散列算法是:md5(md5(密码+username+salt2)))。
CodedqRealm 代码如下:
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = "codedq"; //用户名及salt1
String password = "202cb962ac59075b964b07152d234b70"; //加密后的密码
String salt2 = "202cb962ac59075b964b07152d234b70";
SimpleAuthenticationInfo ai =
new SimpleAuthenticationInfo(username, password, getName());
ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数
return ai;
}
此处就是把上面的散列值生成的相应数据组装为SimpleAuthenticationInfo,通过SimpleAuthenticationInfo的credentialsSalt设置盐,HashedCredentialsMatcher会自动识别这个盐。
如果使用JdbcRealm,需要修改获取用户信息(包括盐)的sql:“select password, password_salt from users where username = ?”,而我们的盐是由username+password_salt组成,所以需要通过如下ini配置(shiro-jdbc-hashedCredentialsMatcher.ini)修改:
jdbcRealm.saltStyle=COLUMN jdbcRealm.authenticationQuery=select password, concat(username,password_salt) from users where username = ? jdbcRealm.credentialsMatcher=$credentialsMatcher
- saltStyle表示使用密码+盐的机制,authenticationQuery第一列是密码,第二列是盐;
- 通过authenticationQuery指定密码及盐查询SQL;
此处还要注意Shiro默认使用了apache commons BeanUtils,默认是不进行Enum类型转型的,此时需要自己注册一个Enum转换器“BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);”
Shiro 密码重试次数限制
如在1个小时内密码最多重试5次,如果尝试次数超过5次就锁定1小时,1小时后可再次重试,如果还是重试失败,可以锁定如1天,以此类推,防止密码被暴力破解。我们通过继承HashedCredentialsMatcher,且使用Ehcache记录重试次数和超时时间。
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
String username = (String)token.getPrincipal();
//retry count + 1
Element element = passwordRetryCache.get(username);
if(element == null) {
element = new Element(username , new AtomicInteger(0));
passwordRetryCache.put(element);
}
AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
if(retryCount.incrementAndGet() > 5) {
//if retry count > 5 throw
throw new ExcessiveAttemptsException();
}
boolean matches = super.doCredentialsMatch(token, info);
if(matches) {
//clear retry count
passwordRetryCache.remove(username);
}
return matches;
}
如上代码逻辑比较简单,即如果密码输入正确清除cache中的记录;否则cache中的重试次数+1,如果超出5次那么抛出异常表示超出重试次数了。
本文案例代码下载链接:http://pan.baidu.com/s/1slNLiSt 密码:y5ux

: » Shiro 密码重试次数限制
原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/251547.html