visionzheng 2020-01-29
shiro内置了几个密码校验的类,有 Md5CredentialsMatcher Sha1CredentialsMatcher , 不过从1.1版本开始,都开始使用 HashedCredentialsMatcher 这个类了,通过配置加密规则来校验
它们都实现了一个接口 CredentialsMatcher ,我这里也实现这个接口,实现一个自己的密码校验。
新建MyCredentialsMatcher.java
package cn.ishangit.neucommunity.config; import cn.ishangit.neucommunity.service.UserService; import cn.ishangit.neucommunity.util.CommunityUtil; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.springframework.beans.factory.annotation.Autowired; import java.util.Objects; /** * @author Chen * @Description 自定义shiro密码比较器 * @create 2020-01-29 21:21 */ public class MyCredentialsMatcher implements CredentialsMatcher { @Autowired private UserService userService; @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { UsernamePasswordToken utoken=(UsernamePasswordToken) token; //获得用户输入的密码:(可以采用加盐(salt)的方式去检验) String inPassword = new String(utoken.getPassword()); String username = utoken.getUsername(); //获得数据库中的密码 String dbPassword = (String) info.getCredentials(); SimpleAuthenticationInfo saInfo = (SimpleAuthenticationInfo)info; String salt = userService.findUserByName(username).getSalt(); inPassword = CommunityUtil.md5(inPassword+salt); //进行密码的比对 boolean flag = Objects.equals(inPassword, dbPassword); return flag; } }
配置自己的密码校验类替换默认的:由于是springboot,我们直接在配置类ShiroConfig里面配置:
/** * 创建DefaultWebSecurityManager * @return */ @Bean("securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); getUserRealm().setCredentialsMatcher(myCredentialsMatcher()); //关联UserRealm securityManager.setRealm(getUserRealm()); return securityManager; } /** * 配置加密方式 * @return */ @Bean public MyCredentialsMatcher myCredentialsMatcher() { return new MyCredentialsMatcher(); }
此时我们的密码校验类就替换成了我们自己的。