关于Shiro使用密码加密加盐之后序列化失败的问题(十四)

原文:https://blog.csdn.net/qq_34021712/article/details/84567437

shiro使用密码加盐之后,序列化失败 ERROR Failed to serialize

之前的博客一直都是使用的明文存储,一直没有写对密码进行加密、加盐处理,有很长时间没有写关于shiro的博客了,期间有很多人加我咨询shiro的问题,今天有个哥们说使用密码加盐后出现序列化失败的问题,找了一下原因,最后记录到博客,希望能给遇到此问题的人一些帮助。

原shiro配置

这里只贴出来造成序列化失败相关的配置,完整的原始配置参考:https://blog.csdn.net/qq_34021712/article/details/80791339

/**
 * @author: wangsaichao
 * @date: 2018/5/10
 * @description: Shiro配置
 */
@Configuration
public class ShiroConfig {


    /**
     *  身份认证realm; (这个需要自己写,账号密码校验;权限等)
     * @return
     */
    @Bean
    public ShiroRealm shiroRealm(){
        ShiroRealm shiroRealm = new ShiroRealm();
        shiroRealm.setCachingEnabled(true);
        //启用身份验证缓存,即缓存AuthenticationInfo信息,默认false
        shiroRealm.setAuthenticationCachingEnabled(true);
        //缓存AuthenticationInfo信息的缓存名称 在ehcache-shiro.xml中有对应缓存的配置
        shiroRealm.setAuthenticationCacheName("authenticationCache");
        //启用授权缓存,即缓存AuthorizationInfo信息,默认false
        shiroRealm.setAuthorizationCachingEnabled(true);
        //缓存AuthorizationInfo信息的缓存名称  在ehcache-shiro.xml中有对应缓存的配置
        shiroRealm.setAuthorizationCacheName("authorizationCache");
        //配置自定义密码比较器
        shiroRealm.setCredentialsMatcher(retryLimitHashedCredentialsMatcher());
        return shiroRealm;
    }

    /**
     * 配置密码比较器
     * @return
     */
    @Bean("credentialsMatcher")
    public RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher(){
        RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher = new RetryLimitHashedCredentialsMatcher();
        retryLimitHashedCredentialsMatcher.setRedisManager(redisManager());

        //如果密码加密,可以打开下面配置
        //加密算法的名称
        //retryLimitHashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //配置加密的次数
        //retryLimitHashedCredentialsMatcher.setHashIterations(1024);
        //是否存储为16进制
        //retryLimitHashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);

        return retryLimitHashedCredentialsMatcher;
    }

}

其中有一个RetryLimitHashedCredentialsMatcher类 是密码比较器,该类继承于SimpleCredentialsMatcher 由于要进行密码加密加盐处理,所以要更改 RetryLimitHashedCredentialsMatcher 继承 HashedCredentialsMatcher

public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    // 具体内容省略 ......
}

并将 ShiroConfig中的 注释掉的3行打开:

/**
     * 配置密码比较器
     * @return
     */
    @Bean("credentialsMatcher")
    public RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher(){
        RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher = new RetryLimitHashedCredentialsMatcher();
        retryLimitHashedCredentialsMatcher.setRedisManager(redisManager());

        //如果密码加密,可以打开下面配置
        //加密算法的名称
        retryLimitHashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //配置加密的次数
        retryLimitHashedCredentialsMatcher.setHashIterations(1024);
        //是否存储为16进制
        retryLimitHashedCredentialsMatcher.setStoredCredentialsHexEncoded(tru);

        return retryLimitHashedCredentialsMatcher;
    }

修改ShiroRealm中的验证用户身份代码
在这里插入图片描述
然后使用以下代码提前将test用户的密码加密加盐处理放入数据库中,方便测试用:
在这里插入图片描述
最后启动项目,输入test/123456进行登录,报以下异常:

2018/11/26 21:23:22.381 c.s.t.s.global.utils.SerializeUtils [] ERROR Failed to serialize
java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource

序列化失败,SerializeUtils是自己写的一个序列化工具,完整内容可以看一下之前的博客,序列化失败的原因就是因为SimpleByteSource不能被序列化,原因如下:

首先是SerializeUtils的序列化方法,其中objectOutputStream.writeObject(object);是真正的执行序列化操作

在这里插入图片描述
首先是序列化SimpleAuthenticationInfo

在这里插入图片描述
SimpleAuthenticationInfo类中有个属性ByteSource,默认使用的是SimpleByteSource 就是因为该属性无法序列化导致的

在这里插入图片描述

解决方案

第一种:取消authenticationCache

在上面的 shiroRealm 配置中 我们开启了两个缓存:authenticationCacheauthorizationCache 序列化失败的原因就是 因为开启了 authenticationCache 可以将 authenticationCache对应的那两行配置 删除,只缓存 authorizationCache

第二种:自定义ByteSource的实现类

遇见这种自定义实现类,大家首先肯定想的是:写一个类继承SimpleByteSource 然后实现序列化接口,如下:

/**
 * @author: wangsaichao
 * @date: 2018/11/27
 * @description:
 */
public class MySimpleByteSource extends SimpleByteSource implements Serializable{

    public MySimpleByteSource(String salt) {
        super(salt);
    }

}

然后在自定义的Realm中的doGetAuthenticationInfo方法中,返回SimpleAuthenticationInfo如下:

return new SimpleAuthenticationInfo(user, user.getPassword(),new MySimpleByteSource(user.getUsername()),getName());

注意:经过测试,在序列化的时候不报错,但是在反序列化的时候就报错了:

2018/11/27 11:50:21.090 c.s.t.s.global.utils.SerializeUtils [] ERROR Failed to deserialize
java.io.InvalidClassException: com.springboot.test.shiro.config.shiro.MySimpleByteSource; no valid constructor

因为在 SimpleByteSource 不存在 默认的无参构造器, 当 不存在无参构造器 或者 访问权限设置为private、默认或protected级别,会抛出java.io.InvalidException: no valid constructor异常。

正确的解决办法

SimpleByteSource整个类 复制粘贴 给个名字 叫MyByteSource,额外实现Serializable接口,并添加无参构造器

/**
 * @author: wangsaichao
 * @date: 2018/11/27
 * @description: 解决 SimpleByteSource 无法序列化的问题
 */
public class MyByteSource implements ByteSource,Serializable {

    private byte[] bytes;
    private String cachedHex;
    private String cachedBase64;

    public MyByteSource() {
    }

    public MyByteSource(byte[] bytes) {
        this.bytes = bytes;
    }


    public MyByteSource(char[] chars) {
        this.bytes = CodecSupport.toBytes(chars);
    }


    public MyByteSource(String string) {
        this.bytes = CodecSupport.toBytes(string);
    }


    public MyByteSource(ByteSource source) {
        this.bytes = source.getBytes();
    }


    public MyByteSource(File file) {
        this.bytes = new MyByteSource.BytesHelper().getBytes(file);
    }


    public MyByteSource(InputStream stream) {
        this.bytes = new MyByteSource.BytesHelper().getBytes(stream);
    }

    public static boolean isCompatible(Object o) {
        return o instanceof byte[] || o instanceof char[] || o instanceof String ||
                o instanceof ByteSource || o instanceof File || o instanceof InputStream;
    }

    @Override
    public byte[] getBytes() {
        return this.bytes;
    }

    @Override
    public boolean isEmpty() {
        return this.bytes == null || this.bytes.length == 0;
    }

    @Override
    public String toHex() {
        if ( this.cachedHex == null ) {
            this.cachedHex = Hex.encodeToString(getBytes());
        }
        return this.cachedHex;
    }

    @Override
    public String toBase64() {
        if ( this.cachedBase64 == null ) {
            this.cachedBase64 = Base64.encodeToString(getBytes());
        }
        return this.cachedBase64;
    }

    @Override
    public String toString() {
        return toBase64();
    }

    @Override
    public int hashCode() {
        if (this.bytes == null || this.bytes.length == 0) {
            return 0;
        }
        return Arrays.hashCode(this.bytes);
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (o instanceof ByteSource) {
            ByteSource bs = (ByteSource) o;
            return Arrays.equals(getBytes(), bs.getBytes());
        }
        return false;
    }

    //will probably be removed in Shiro 2.0.  See SHIRO-203:
    //https://issues.apache.org/jira/browse/SHIRO-203
    private static final class BytesHelper extends CodecSupport {

        /**
         * 嵌套类也需要提供无参构造器
         */
        private BytesHelper() {
        }

        public byte[] getBytes(File file) {
            return toBytes(file);
        }

        public byte[] getBytes(InputStream stream) {
            return toBytes(stream);
        }
    }

}

然后在自定义的Realm中的doGetAuthenticationInfo方法中,返回SimpleAuthenticationInfo如下:

return new SimpleAuthenticationInfo(user, user.getPassword(),new MyByteSource(user.getUsername()),getName());
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值