/**
* 领域
*/
@Bean(name = "myShiroRealm")
@DependsOn(value = {"lifecycleBeanPostProcessor", "ShiroRedisCacheManager"})
public MyShiroRealm myShiroRealm(@Qualifier("shiroRedisTemplate")RedisTemplate redisTemplate) {
MyShiroRealm shiroRealm = new MyShiroRealm();
//设置缓存管理器
shiroRealm.setCacheManager(redisCacheManager());
shiroRealm.setCachingEnabled(true);
//设置认证密码算法及迭代复杂度
shiroRealm.setCredentialsMatcher(retryLimitHashedCredentialsMatcher());
//认证
shiroRealm.setAuthenticationCachingEnabled(true);
//授权
shiroRealm.setAuthorizationCachingEnabled(true);
return shiroRealm;
}
public class MyShiroRealm extends AuthorizingRealm {
@Autowired
private RoleMapper roleMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private AuthorityMapper authorityMapper;
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
User user = (User) principals.getPrimaryPrincipal();
System.out.println(user.getUsername() + "进行授权操作");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Integer roleId = user.getRoleId();
Role role = roleMapper.selectByPrimaryKey(roleId);
info.addRole(role.getRoleName());
List<Authority> authorities = authorityMapper.selectByRoleId(roleId);
return CollectionUtils.isEmpty(authorities) ? null : info;
}
/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
//根据用户名查询密码,由安全管理器负责对比查询出的数据库中的密码和页面输入的密码是否一致
User user = userMapper.findUserByUserName(username);
if (user == null) {
return null;
}
if (1==user.getState()) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
String password = user.getPassword();
//最后的比对需要交给安全管理器,三个参数进行初步的简单认证信息对象的包装,由安全管理器进行包装运行
return new SimpleAuthenticationInfo(user, password, new MySimpleByteSource(ByteSourceUtils.serialize(user.getUsername())),getName());
}
其中盐值加密的时候会出现序列化异常,自己实现序列化类
/**
* 解决:
* shiro 使用缓存时出现:java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource
* 序列化后,无法反序列化的问题
*/
public class MySimpleByteSource implements ByteSource, Serializable {
private static final long serialVersionUID = 5175082362119580768L;
private byte[] bytes;
private String cachedHex;
private String cachedBase64;
public MySimpleByteSource(){
}
public MySimpleByteSource(byte[] bytes) {
this.bytes = bytes;
}
public MySimpleByteSource(char[] chars) {
this.bytes = CodecSupport.toBytes(chars);
}
public MySimpleByteSource(String string) {
this.bytes = CodecSupport.toBytes(string);
}
public MySimpleByteSource(ByteSource source) {
this.bytes = source.getBytes();
}
public MySimpleByteSource(File file) {
this.bytes = (new MySimpleByteSource.BytesHelper()).getBytes(file);
}
public MySimpleByteSource(InputStream stream) {
this.bytes = (new MySimpleByteSource.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;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public byte[] getBytes() {
return this.bytes;
}
@Override
public String toHex() {
if(this.cachedHex == null) {
this.cachedHex = Hex.encodeToString(this.getBytes());
}
return this.cachedHex;
}
@Override
public String toBase64() {
if(this.cachedBase64 == null) {
this.cachedBase64 = Base64.encodeToString(this.getBytes());
}
return this.cachedBase64;
}
@Override
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
@Override
public String toString() {
return this.toBase64();
}
@Override
public int hashCode() {
return this.bytes != null && this.bytes.length != 0? Arrays.hashCode(this.bytes):0;
}
@Override
public boolean equals(Object o) {
if(o == this) {
return true;
} else if(o instanceof ByteSource) {
ByteSource bs = (ByteSource)o;
return Arrays.equals(this.getBytes(), bs.getBytes());
} else {
return false;
}
}
private static final class BytesHelper extends CodecSupport {
private BytesHelper() {
}
public byte[] getBytes(File file) {
return this.toBytes(file);
}
public byte[] getBytes(InputStream stream) {
return this.toBytes(stream);
}
}
}
/**
* 序列化与反序列化
*/
@SuppressWarnings("unchecked")
public class ByteSourceUtils {
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
System.out.println("serialize error");
} finally {
close(os);
close(bos);
}
return rv;
}
public static Object deserialize(byte[] in) {
return deserialize(in, Object.class);
}
public static <T> T deserialize(byte[] in, Class<T>...requiredType) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("deserialize error");
} finally {
close(is);
close(bis);
}
return (T) rv;
}
private static void close(Closeable closeable) {
if (closeable != null){
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("close stream error");
}
}
}
}