SpringBoot集成Shiro、Redis,开启权限缓存,序列化SimpleAuthenticationInfo对象与AuthenticationInfo对象不匹配

1、场景

新建RedisCacheManager类,实现CacheManager,重写getCache(Stirng name)

/**
* @Description: RedisCacheManager 实例
* @author chenhang
* @date 2019年6月13日
*/
public class RedisCacheManager implements CacheManager{

	@Resource
    private RedisCache redisCache;
	
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		return redisCache;
	}
}

集成Redis,将数据存放至Redis

package com.shiro.cache;

import com.shiro.util.JedisUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;

/**
* @Description: cache实例
* @author chenhang
* @date 2019年6月13日
*/
@SuppressWarnings("unchecked")
@Component
public class RedisCache<K, V> implements Cache<K, V>{
	
	@Resource
    private JedisUtil jedisUtil;

	private final String CACHE_PREFIX = "jack-cache";
	
	private byte[] getKey(K k) {
		if (k instanceof String) {
			return (CACHE_PREFIX+k).getBytes();
		}
		return SerializationUtils.serialize(k);
	}
	
	@Override
	public V get(K k) throws CacheException {
        byte[] value = jedisUtil.get(getKey(k));
        if (value != null) {
            return (V) SerializationUtils.deserialize(value);
        }
        return null;
	}
	    
	@Override
	public V put(K k, V v) throws CacheException {
		byte[] key = getKey(k);
        byte[] value = SerializationUtils.serialize(v);
        jedisUtil.set(key, value);
        jedisUtil.expire(key, 600);
        return v;
	}
	    
	@Override
	public V remove(K k) throws CacheException {
		byte[] key = getKey(k);
        byte[] value = SerializationUtils.serialize(key);
        jedisUtil.del(key);
        if (value != null) {
            return (V) SerializationUtils.deserialize(value);
        }
        return null;
	}

	@Override
	public void clear() throws CacheException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return 0;
	}
	    
	@Override
	public Set<K> keys() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Collection<V> values() {
		// TODO Auto-generated method stub
		return null;
	}

}

在自定义realm中设置开启缓存,并开启角色权限缓存

  @Bean
    public UserRealm userRealm() {
    	UserRealm1 userRealm = new UserRealm1();
    	userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
    	userRealm.setCachingEnabled(true);
        userRealm.setAuthenticationCachingEnabled(true);
        userRealm.setAuthorizationCachingEnabled(true);
        userRealm.setCacheManager(new RedisCacheManager());
        return userRealm;
    }

然后项目启动,RedisCache.put()方法序列化后(v为SimpleAuthenticationInfo对象),源码文件AuthenticatingRealm调用cache.get(key)返回值与AuthenticationInfo对象不匹配。

 private AuthenticationInfo getCachedAuthenticationInfo(AuthenticationToken token) {
        AuthenticationInfo info = null;

        Cache<Object, AuthenticationInfo> cache = getAvailableAuthenticationCache();
        if (cache != null && token != null) {
            log.trace("Attempting to retrieve the AuthenticationInfo from cache.");
            Object key = getAuthenticationCacheKey(token);
            info = cache.get(key);
            if (info == null) {
                log.trace("No AuthorizationInfo found in cache for key [{}]", key);
            } else {
                log.trace("Found cached AuthorizationInfo for key [{}]", key);
            }
        }

        return info;
    }

 2、解决方案

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

第二种:自定义ByteSource的实现类
SimpleByteSource整个类 复制粘贴 给个名字 叫MyByteSource,额外实现Serializable接口,并添加无参构造器

/**
* @Description: MyByteSource 解决序列化问题
* @author chenhang
* @date 2019年6月13日
*/
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(userName, password,new MyByteSource(userName + "salt"),getName());

源码地址:https://github.com/chenhang666/Shiro_Demo

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值