九、密码比较
2019-10-11 本文已影响0人
凌晨丶杨先森灬
在这里插入图片描述在realm中 认证成功后会返回 return new SimpleAuthenticationInfo(username,md5, getName());
在这里插入图片描述认证成功成功拿到 info 放下执行到 assertCredentialsMatch(token,info);
public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
CredentialsMatcher cm = getCredentialsMatcher();
if (cm != null) {
if (!cm.doCredentialsMatch(token, info)) {
//not successful - throw an exception to indicate this:
String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
} else {
throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
"credentials during authentication. If you do not wish for credentials to be examined, you " +
"can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
}
}
}
在这里插入图片描述cm.doCredentialsMatch(token, info) 这里可以使用默认的密码比较器 或者使用自定义的密码比较
我这里是自定义 密码校验 很简单就是继承上面图中的类 画横线的过时了 实现doCredentialsMatch 方法
public class Md5HashCredentialsMatcher extends SimpleCredentialsMatcher {
@Override
public boolean doCredentialsMatch(AuthenticationToken token,
AuthenticationInfo info) {
UsernamePasswordToken usertoken = (UsernamePasswordToken) token;
//注意token.getPassword()拿到的是一个char[],不能直接用toString(),它底层实现不是我们想的直接字符串,只能强转
Object tokenCredentials = Encrypt.md5(String.valueOf(usertoken.getPassword()), usertoken.getUsername());
Object accountCredentials = getCredentials(info);
//将密码加密与系统加密后的密码校验,内容一致就返回true,不一致就返回false
return equals(tokenCredentials, accountCredentials);
}
}
然后在spring-shiro.xml 中配置一下
<bean id="myRealm" class="spring.shiro.realm.MyRealm">
<property name="credentialsMatcher" ref="md5Matcher"/>
<!--<property name="credentialsMatcher" ref="md5hash"/>-->
</bean>
<bean id="md5hash" class="spring.shiro.matcher.Md5HashCredentialsMatcher"/>
<bean id="md5Matcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密算法的名称 -->
<property name="hashAlgorithmName" value="MD5"/>
<!-- 配置加密的次数 -->
<property name="hashIterations" value="1024"/>
</bean>
<bean id="sha1Matcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密算法的名称 -->
<property name="hashAlgorithmName" value="SHA1"/>
<!-- 配置加密的次数 -->
<property name="hashIterations" value="1024"/>
</bean>