shiro自定义密码校验器
shiro自定义密码校验器
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(); }
此时我们的密码校验类就替换成了我们自己的。
相关推荐
xclxcl 2020-08-03
zmzmmf 2020-08-03
likesyour 2020-08-01
杜鲁门 2020-11-05
luckyxl0 2020-08-16
Dullonjiang 2020-08-09
MicroBoy 2020-08-02
ganjing 2020-08-02
zmzmmf 2020-07-09
MicroBoy 2020-07-05
zzhao 2020-06-26
子云 2020-06-18
visionzheng 2020-06-07
neweastsun 2020-06-04
ErixHao 2020-06-03
GDreams0 2020-06-01
ganjing 2020-05-29
zmzmmf 2020-05-28
nullcy 2020-05-26