现在的这个自定义是realm,如下所示,需要重写三个方法。同时,在验证方法中,需要从数据库中,获取密码,告诉加盐形式。我们来看具体参数。
public class PasswordRealm extends AuthorizingRealm {
@Override
public String getName() {
return super.getName();
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println(token);
//获取token的用户名
String username = (String) token.getPrincipal();
if (!"zhangsan".equals(username)){
return null;
}
//加密,加盐,散列
String password="b51ae3e5279bc66eae7a4fe2600ab0b1";
//参数一:当前登陆用户名,参数二:数据库的密码,参数三:加盐,参数三:当前realm的名字
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
username, password, ByteSource.Util.bytes("zhangsan"), getName());
//org.apache.shiro.authc.credential.HashedCredentialsMatcher
return info;
}
}
然后我们来看一下测试代码,如下所示。
public void md5test() throws Exception{
String password="123456";
Md5Hash md5Hash = new Md5Hash(password);
System.out.println(md5Hash);
//加盐
md5Hash=new Md5Hash(password,"zhangsan");
System.out.println(md5Hash);
//散列次数
md5Hash=new Md5Hash(password,"zhangsan",3);
System.out.println(md5Hash);
//org.apache.shiro.credential.HashedCredentialsMatcher
}
再来看一下ini文件。
[main]
#定义认证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#散列次数
credentialsMatcher.hashIterations=3
#将凭证匹配到设置的realm
myRealm=ShrioTest.PasswordRealm
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm