shiro:HashedCredentialsMatcher认证匹配

x33g5p2x  于2021-10-18 转载在 其他  
字(2.1k)|赞(0)|评价(0)|浏览(417)

1、HashedCredentialsMatcher类的介绍

shiro提供了用于加密密码和验证密码服务的CredentialsMatcher 接口,而 HashedCredentialsMatcher 正是 CredentialsMatcher 的一个实现类写项目的话,总归会用到用户密码的非对称加密,目前主流的非对称加密方式是 MD5 ,以及在 MD5 上的加盐处理,而 HashedCredentialsMatcher 也允许我们指定自己的算法和盐

2、HashedCredentialsMatcher 的使用

1.建立 ShiroConfiguration 配置类,除了 shiro 的通常配置之外,需加上:

@Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
      	//加密方式
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
      	//加密次数
        hashedCredentialsMatcher.setHashIterations(2);
      	//存储散列后的密码是否为16进制
      	hashedCredentialsMatcher.isStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }

2.XML 格式

<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
  		<!-- 加密方式 -->
        <property name="hashAlgorithmName" value="MD5" />
  		<!-- 加密次数 -->
        <property name="hashIterations" value="2" />
  		<!-- 存储散列后的密码是否为16进制 -->
        <property name="storedCredentialsHexEncoded" value="true" />
</bean>

3.ini 等配置文件

首先在 web.xml 中自定义 shiro.ini 位置

<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>
    <init-param>
        <param-name>configPath</param-name>
        <param-value>/WEB-INF/shiro.ini</param-value>
    </init-param>
</filter>

然后除了 shiro 的通常配置之外,需加上:

credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
## 加密方式
credentialsMatcher.hashAlgorithmName=md5
## 加密次数
credentialsMatcher.hashIterations=2
## 存储散列后的密码是否为16进制 
credentialsMatcher.storedCredentialsHexEncoded=true

3、HashedCredentialsMatcher 的源码分析

从开发者的角度来看,我们可以自己实现 CredentialsMatcher 的一个类来实现定制化的账户密码验证机制,例如

public class MyCredentialsMatcher extends SimpleCredentialsMatcher {
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
          Object tokenCredentials = getCredentials(token);
        Object accountCredentials = getCredentials(info);
        return super.equals(tokenCredentials, accountCredentials);
    }
}

相关文章