目录
1、什么是凭证比较器
在第一章,shiro整体架构图上可以看到,shiro为我们提供了密码学工具,和哈希凭据匹配器 HashedCredentialsMatcher 类,下图可以看到此类继承了编解码支持器 CodecSupport 类和实现了 CredentialsMatcher 接口,实现了接口中 boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) 方法,这个方法就可以替我们实现密码比较,他会在调用自定义realm的身份认证方法后来执行!
2、为什么要加密加盐
- 之前的例子中,我们在自定义realm的 doGetAuthenticationInfo 方法中采用了自己加密和对比密码,不同则抛出 IncorrectCredentialsException 异常的方式对比密码,但是在继续深入学习shiro的过程中,发现了shiro已经为我们提供了自动密码比对工具,我们只要安装上去即可使用。之后会讲到他的执行原理和使用方法。
- 那么为什么要对数据加密呢?这篇文章可以告诉你答案2018年国内外信息泄露案例汇编,现在数据库加密基本上是使用MD5加密方式,MD5加密过的密文只能被暴力破解,我们不仅仅是要防范外部黑客的攻击,还需要放置内部维护人员猜出密码,加密过后,即使数据库被泄露出去,但是暴露出去的人员的密码均是加密过的,这样即使是暴力破解,也给予了时间挽救。
- 为什么要加盐呢,盐就是让你的密码更加的安全,更加的难以破解,在你的密码中加入特定的字段,然后在进行加密,这样即使密码相同的情况下,只要盐不相同,数据库储存的字段也不会相同,大大减少了很多用户使用同一密码,数据库泄漏一下破解很多用户账号的可能!
3、如何生成密文
shiro已经为我们提供了密码学工具,SimpleHash 类,我们只需要调用这个类的方法即可快速完成密码加密,查看关系图,猜测此类还提供sha加密方式(后认证过),
String hashAlgorithmName = "MD5";//加密方式
Object crdentials = "admin";//密码原值
ByteSource salt = ByteSource.Util.bytes("admin");//以账号作为盐值
int hashIterations = 1024;//加密次数
Object result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations);
System.out.println("admin:"+result);
//输出
>> admin:df655ad8d3229f3269fad2a8bab59b6c
用户注册时,可以使用此方法生成密文
4、了解shiro自带凭证比较器
我们跟踪登录流程发现用户调用login接口后,shiro框架会执行下列流程:
下面为 HashedCredentialsMatcher 哈希凭据匹配器 的继承关系
4.1提供的的比较凭证的方法部分代码
//固有属性
private String hashAlgorithm; // 加密算法的名称
private int hashIterations; // 配置加密的次数
private boolean hashSalted;//是否加盐
private boolean storedCredentialsHexEncoded;// 是否存储为16进制
//构造
public HashedCredentialsMatcher() {
this.hashAlgorithm = null;
this.hashSalted = false;
this.hashIterations = 1;
this.storedCredentialsHexEncoded = true; //false means Base64-encoded
}
//设置凭证加密次数
public void setHashIterations(int hashIterations) {
if (hashIterations < 1) {//在此限制了最低加密次数为1次
this.hashIterations = 1;
} else {
this.hashIterations = hashIterations;
}
}
...............
//实现对比凭证方法,token中包含用户输入信息,info则是realm中用户认证方法中返回的dbuser信息
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
Object tokenCredentials = getCredentials(token);
Object accountCredentials = getCredentials(info);
return equals(tokenCredentials, accountCredentials);
}
5、使用shiro自带凭证比较器
- 需要在shiroconfig配置类中新增凭证比较器
@Bean
public SimpleCredentialsMatcher CredentialsMatcher() {
HashedCredentialsMatcher hct = new HashedCredentialsMatcher();
// 加密算法的名称
hct.setHashAlgorithmName("MD5");
// 配置加密的次数
hct.setHashIterations(1024);
// 是否存储为16进制
hct.setStoredCredentialsHexEncoded(true);
return hct;
}
- 把凭证比较器放入自定义realm中,如果没有此步骤shiro不会进行凭证验证
/**
* 自定义身份认证 realm;
* <p>
* 必须写这个类,并加上 @Bean 注解,目的是注入 MyShiroRealm, 否则会影响 MyShiroRealm类 中其他类的依赖注入
*/
@Bean
public MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
// 设置凭证比较器
myShiroRealm.setCredentialsMatcher(CredentialsMatcher());
return myShiroRealm;
}
- 修改用户信息,模拟用户注册生成的密码,更新至业务层
我们采用guest用户来测试,使用用户名guest作为盐,把生成的密码放入service中,
String hashAlgorithmName = "MD5";//加密方式
Object crdentials = "guest";//密码原值
ByteSource salt = ByteSource.Util.bytes("guest");//以账号作为盐值
int hashIterations = 1024;//加密次数
Object result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations);
System.out.println("admin:"+result);
>>admin:565dd969076eef0ac3f9d49aa61e9489
- 更新UserServiceImpl
@Override
public User findByUsername(String username) {
User user = new User();
user.setUsername(username);
Set<String> roleList = new HashSet<>();
Set<String> permissionsList = new HashSet<>();
switch (username) {
case "admin":
roleList.add("admin");
user.setPassword("admin");
permissionsList.add("user:add");
permissionsList.add("user:delete");
break;
case "consumer":
roleList.add("consumer");
user.setPassword("consumer");
permissionsList.add("consumer:modify");
break;
default:
roleList.add("guest");
user.setPassword("565dd969076eef0ac3f9d49aa61e9489");
break;
}
user.setRole(roleList);
user.setPermission(permissionsList);
return user;
}
- 把自定义realm中的判断密码部分代码删除,此时,我们可以把这个方法理解为提供给主框架真实用户信息,作为凭证对比对象
/**
* 身份验证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("进入自定义登录验证方法!");
if (userService == null) {
userService = (UserService) SpringBeanFactoryUtil.getBeanByName("userServiceImpl");
}
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String username = usernamePasswordToken.getUsername();// 用户输入用户名
User user = userService.findByUsername(username);// 根据用户输入用户名查询该用户
if (user == null) {
throw new UnknownAccountException();// 用户不存在
}
String password = user.getPassword();// 数据库获取的密码
// 主要的(用户名,也可以是用户对象(最好不放对象)),资格证书(数据库获取的密码),区域名称(当前realm名称)
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
//加盐,对比的时候会使用该参数对用户输入的密码按照密码比较器指定规则加盐,加密,再去对比数据库密文
simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
return simpleAuthenticationInfo;
}
5.1登录测试,可以登录
- 此时我们断点到shiro的凭证对比器中查看,可以看到shiro内部已经使用 hashProvidedCredentials 方法对输入的密码进行了加密
- 部分源码
//HashedCredentialsMatcher类 密码加密
protected Object hashProvidedCredentials(AuthenticationToken token, AuthenticationInfo info) {
Object salt = null;
if (info instanceof SaltedAuthenticationInfo) {
salt = ((SaltedAuthenticationInfo) info).getCredentialsSalt();
} else {
//retain 1.0 backwards compatibility:
if (isHashSalted()) {
salt = getSalt(token);
}
}
return hashProvidedCredentials(token.getCredentials(), salt, getHashIterations());
}
@Override //HashedCredentialsMatcher类
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
Object tokenHashedCredentials = hashProvidedCredentials(token, info);
Object accountCredentials = getCredentials(info);
return equals(tokenHashedCredentials, accountCredentials);
}
//密码对比方法SimpleCredentialsMatcher类
protected boolean equals(Object tokenCredentials, Object accountCredentials) {
.......
if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
....
byte[] tokenBytes = toBytes(tokenCredentials);
byte[] accountBytes = toBytes(accountCredentials);
return MessageDigest.isEqual(tokenBytes, accountBytes);
} else {
return accountCredentials.equals(tokenCredentials);
}
}
6、如何使用自定义密码比较器
- 在理解了shiro自带的凭证比较器后,自定义一个自己的凭证比较器思路应该也十分清晰了,我们只需要创建 MyCredentialsMatcher 类继承 SimpleCredentialsMatcher 类,重写其中的 doCredentialsMatch 方法即可
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
public class MyCredentialsMatcher extends SimpleCredentialsMatcher {
/**
* 重写密码验证器
*
* @param token 用户输入的信息
* @param info 数据库查询到的信息
*/
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
System.out.println("进入自定义密码比较器");
UsernamePasswordToken upt = (UsernamePasswordToken) token;
String inputName = upt.getUsername();// 用户输入的用户名
String inputPwd = new String(upt.getPassword());// 用户输入的密码
String dbPassword = (String) info.getCredentials();// 数据库查询得到的加密后的密码
// 对用户输入密码进行加密(加密方式,用户输入密码,盐值(用户名),加密次数)
String encryptionPwd = new SimpleHash("MD5", inputPwd, inputName, 1024).toString();// 加密后的密码
return equals(encryptionPwd, dbPassword);
}
}
- 第二步,我们需要把注入realm的凭证比较器替换为我们自己的凭证比较器
@Bean
public SimpleCredentialsMatcher CredentialsMatcher() {
MyCredentialsMatcher hct = new MyCredentialsMatcher();//自定义凭证比较器
//HashedCredentialsMatcher hct = new HashedCredentialsMatcher();//系统提供凭证比较器
// 加密算法的名称
hct.setHashAlgorithmName("MD5");
// 配置加密的次数
hct.setHashIterations(1024);
// 是否存储为16进制
hct.setStoredCredentialsHexEncoded(true);
return hct;
}
6.1 测试
控制台打印出了执行了自定义密码