根本原因:密码匹配不对应
1.首先先检查是否使用了加密,如果使用了加密方式,那么有可能就是你数据库中存储的密码是明文形式的密码,所以两者无法匹配。
因为我在shiro里面对密码 进行了MD5加密,所以这和我们一般的密码匹配还不一样。
首先先检查我们对于shiro的配置文件信息
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <!--声明加密算法--> <property name="hashAlgorithmName" value="md5"></property> <!--声明加密次数--> <property name="hashIterations" value="10"></property> <!--存储散列后的密码是否为16进制> <property name="storedCredentialsHexEncoded" value="true"></property> </bean>
这里主要及时对我们的密码加密进行相关的配置。
之后再看我们的UserRealm部分的代码:
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String loginName=authenticationToken.getPrincipal().toString(); UserDao userDao=userService.getUserByLoginName(loginName); if(userDao==null) { throw new UnknownAccountException("账号不存在!"); } if(userDao.getUsageState()==0){ throw new LockedAccountException("账号已锁定!"); } return new SimpleAuthenticationInfo(userDao.getLoginName(),userDao.getPassword(), ByteSource.Util.bytes(loginName),getName());//获取数据库中查到的用户的名称以及密码,之后通过用户名进行加盐加密,ByteSource.Util.bytes(loginName)即为盐值 }
代码中我们是没有问题的,但是我们也需要注意一点,就是SimpleAuthenticationInfo参数中的密码,这里必须要是我们从数据库中取出来的密码即密文形式的密码,如果是直接用的明文形式密码,那么也会报错这点一定要记好。
2. 其次就是既然是从数据库中取出密文形式的密码,那么就必须要保证我们数据库中存储的的确是密文形式的密码,所以我们必须要检查数据库。这里也就是博主错误的地方。
这里附上MD5转换的代码,大家可以通过这个来检测是不是我们所存储的密码。
import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.util.ByteSource; import org.junit.Test; public class PasswordSaltTest { @Test public void test() throws Exception { System.out.println(md5("123","username")); } public static final String md5(String password, String salt){ //加密方式 String hashAlgorithmName = "MD5"; //盐:为了即使相同的密码不同的盐加密后的结果也不同 ByteSource byteSalt = ByteSource.Util.bytes(salt); //密码 Object source = password; //加密次数 int hashIterations = 10; SimpleHash result = new SimpleHash(hashAlgorithmName, source, byteSalt, hashIterations); return result.toString(); } }