定义一个类实现SimpleCredentialsMatcher方法。重写doCredentialsMatch方法
public class CredentialMatcher extends SimpleCredentialsMatcher{
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
UsernamePasswordToken uToken = (UsernamePasswordToken)token;
//后台传入的密码
String password = new String(uToken.getPassword());
//获取数据库存放的的密码
String dbPassword = (String) info.getCredentials();
return this.equals(password,dbPassword);
}
}
其中info.getCredentials()获取到的值为MyRealm中doGetAuthenticationInfo方法
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,
user.getPassword(),this.getClass().getName());
传入的user.getPassword.
在shiroConfig中定义
@Bean
public CredentialMatcher credentialMatcher() {
return new CredentialMatcher();
}
/**
* 注入自定义的realm
* @return
*/
@Bean
public MyRealm myRealm() {
MyRealm realm = new MyRealm();
realm.setCredentialsMatcher(credentialMatcher());
/*
* realm.setCacheManager(ehCacheManager()); //启用身份验证缓存,默认为false
* realm.setAuthenticationCachingEnabled(true); //缓存AuthenticationInfo信息的缓存名称
* 在ehcache-shiro.xml中有对应缓存的配置
* realm.setAuthenticationCacheName("authenticationCache"); //启用权限验证缓存,默认false
* realm.setAuthorizationCachingEnabled(true); //缓存AuthorizationInfo信息的缓存名称
* 在ehcache-shiro.xml中有对应缓存的配置
* realm.setAuthorizationCacheName("authorizationCache");
*/
return realm;
}