session共享

登录缓存清理
缓存更换为redis缓存代码提交
This commit is contained in:
段冬梅
2018-12-16 11:04:25 +08:00
parent 22920b84cc
commit ed45211de9
11 changed files with 310 additions and 82 deletions

View File

@@ -700,6 +700,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>3.2.1</version>
</dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.connectors</groupId> <groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId> <artifactId>jersey-apache-connector</artifactId>

View File

@@ -5,6 +5,7 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.shiro.cache.Cache;
import com.beust.jcommander.internal.Lists; import com.beust.jcommander.internal.Lists;
import com.nis.domain.specific.ConfigGroupInfo; import com.nis.domain.specific.ConfigGroupInfo;
@@ -12,8 +13,6 @@ import com.nis.web.dao.specific.ConfigGroupInfoDao;
import com.nis.web.service.SpringContextHolder; import com.nis.web.service.SpringContextHolder;
import jersey.repackaged.com.google.common.collect.Maps; import jersey.repackaged.com.google.common.collect.Maps;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
/** /**
* asn no缓存工具类 * asn no缓存工具类
@@ -35,9 +34,12 @@ public class AsnCacheUtils{
* @return * @return
*/ */
public static ConfigGroupInfo get(Long key) { public static ConfigGroupInfo get(Long key) {
Element element = getCache(ASN_NO_CACHE).get(key/cache_rage); Cache cache = getCache(ASN_NO_CACHE);
Object element = cache.get(key/cache_rage);
// Element element = getCache(ASN_NO_CACHE).get(key/cache_rage);
if(element!=null) { if(element!=null) {
Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element.getObjectValue(); Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element;
if(map.containsKey(key)) { if(map.containsKey(key)) {
return map.get(key); return map.get(key);
} }
@@ -45,20 +47,19 @@ public class AsnCacheUtils{
return null; return null;
} }
public static Map<Long,ConfigGroupInfo> getMap(Object key) { public static Map<Long,ConfigGroupInfo> getMap(Object key) {
Element element = getCache(ASN_NO_CACHE).get(key); Object element = getCache(ASN_NO_CACHE).get(key);
return (Map<Long,ConfigGroupInfo>)element.getObjectValue(); return (Map<Long,ConfigGroupInfo>)element;
} }
public static void clearCache() { public static void clearCache() {
logger.warn("clear cache!"); logger.warn("clear cache!");
CacheUtils.getCacheManager().removeCache(ASN_NO_CACHE); getCache(ASN_NO_CACHE).clear();
} }
public static List<ConfigGroupInfo> getAllAsnGroup(){ public static List<ConfigGroupInfo> getAllAsnGroup(){
List<ConfigGroupInfo> configGroupInfos=Lists.newArrayList(); List<ConfigGroupInfo> configGroupInfos=Lists.newArrayList();
Cache cache=getCache(ASN_NO_CACHE); Cache cache=getCache(ASN_NO_CACHE);
for(Object key:cache.getKeys()) { for(Object val : cache.values()) {
Element element = getCache(ASN_NO_CACHE).get(key); if(val!=null) {
if(element!=null) { Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)val;
Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element.getObjectValue();
configGroupInfos.addAll(map.values()); configGroupInfos.addAll(map.values());
} }
} }
@@ -89,20 +90,22 @@ public class AsnCacheUtils{
} }
} }
for(Entry<Long, Map<Long, ConfigGroupInfo>> e:groupMap.entrySet()) { for(Entry<Long, Map<Long, ConfigGroupInfo>> e:groupMap.entrySet()) {
Element element = new Element(e.getKey(), e.getValue()); cache.put(e.getKey(),e.getValue());
cache.put(element);
} }
}else { }else {
//查询总量 //查询总量
Long count=configGroupInfoDao.getCountByType(4); Long count=configGroupInfoDao.getCountByType(4);
boolean loadDatabase=false; boolean loadDatabase=false;
if(cache.getKeys().size()==0) { if(cache.keys().size()==0) {
loadDatabase=true; loadDatabase=true;
}else { }else {
long c=0l; long c=0l;
for(Object key:cache.getKeys()) { for(Object key:cache.keys()) {
Map<Long, ConfigGroupInfo> map = getMap(key);
if(map != null) {
c+=getMap(key).size(); c+=getMap(key).size();
} }
}
if(c!=count) { if(c!=count) {
loadDatabase=true; loadDatabase=true;
} }
@@ -121,8 +124,7 @@ public class AsnCacheUtils{
} }
} }
for(Entry<Long, Map<Long, ConfigGroupInfo>> e:groupMap.entrySet()) { for(Entry<Long, Map<Long, ConfigGroupInfo>> e:groupMap.entrySet()) {
Element element = new Element(e.getKey(), e.getValue()); cache.put(e.getKey(), e.getValue());
cache.put(element);
} }
} }
} }
@@ -137,17 +139,16 @@ public class AsnCacheUtils{
*/ */
public static void put(Long key, ConfigGroupInfo value) { public static void put(Long key, ConfigGroupInfo value) {
Long _key=key/cache_rage; Long _key=key/cache_rage;
Element element = getCache(ASN_NO_CACHE).get(_key); Object element = getCache(ASN_NO_CACHE).get(_key);
if(element==null) { if(element==null) {
Map<Long,ConfigGroupInfo> map=Maps.newHashMap(); Map<Long,ConfigGroupInfo> map=Maps.newHashMap();
map.put(key, value); map.put(key, value);
element = new Element(_key, map); getCache(ASN_NO_CACHE).put(_key,map);
}else { }else {
Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element.getObjectValue(); Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element;
map.put(key, value); map.put(key, value);
element = new Element(_key, map); getCache(ASN_NO_CACHE).put(_key,map);
} }
getCache(ASN_NO_CACHE).put(element);
} }
/** /**
* 从缓存中移除 * 从缓存中移除
@@ -159,30 +160,25 @@ public class AsnCacheUtils{
} }
public static void remove(Long key) { public static void remove(Long key) {
Long _key=key/cache_rage; Long _key=key/cache_rage;
Element element = getCache(ASN_NO_CACHE).get(_key); Object element = getCache(ASN_NO_CACHE).get(_key);
if(element!=null) { if(element!=null) {
Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element.getObjectValue(); Map<Long,ConfigGroupInfo> map=(Map<Long,ConfigGroupInfo>)element;
if(map.containsKey(key)) { if(map.containsKey(key)) {
map.remove(key); map.remove(key);
} }
if(map.isEmpty()) { if(map.isEmpty()) {
getCache(ASN_NO_CACHE).remove(_key); getCache(ASN_NO_CACHE).remove(_key);
}else { }else {
element=new Element(_key,map); getCache(ASN_NO_CACHE).put(_key, map);
getCache(ASN_NO_CACHE).put(element);
} }
} }
} }
private static Cache getCache(String cacheName){ private static Cache getCache(String cacheName){
Cache cache = CacheUtils.getCacheManager().getCache(cacheName); Cache cache = CacheUtils.getCacheManager().getCache(cacheName);
if (cache == null){
CacheUtils.getCacheManager().addCache(cacheName);
cache = CacheUtils.getCacheManager().getCache(cacheName);
cache.getCacheConfiguration().setEternal(true);
}
return cache; return cache;
} }
public static String getCacheName() { public static String getCacheName() {
return ASN_NO_CACHE; return ASN_NO_CACHE;
} }

View File

@@ -1,10 +1,11 @@
package com.nis.util; package com.nis.util;
import org.apache.shiro.cache.Cache;
import org.crazycake.shiro.RedisCacheManager;
import com.nis.web.service.SpringContextHolder; import com.nis.web.service.SpringContextHolder;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/** /**
* Cache工具类 * Cache工具类
@@ -13,7 +14,7 @@ import net.sf.ehcache.Element;
*/ */
public class CacheUtils { public class CacheUtils {
private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager")); private static RedisCacheManager cacheManager = (RedisCacheManager)SpringContextHolder.getBean("shiroCacheManager");
private static final String SYS_CACHE = "sysCache"; private static final String SYS_CACHE = "sysCache";
@@ -51,8 +52,7 @@ public class CacheUtils {
* @return * @return
*/ */
public static Object get(String cacheName, String key) { public static Object get(String cacheName, String key) {
Element element = getCache(cacheName).get(key); return getCache(cacheName).get(key);
return element==null?null:element.getObjectValue();
} }
/** /**
@@ -62,8 +62,8 @@ public class CacheUtils {
* @param value * @param value
*/ */
public static void put(String cacheName, String key, Object value) { public static void put(String cacheName, String key, Object value) {
Element element = new Element(key, value); Cache cache=cacheManager.getCache(cacheName);
getCache(cacheName).put(element); cache.put(key, value);
} }
/** /**
@@ -80,7 +80,7 @@ public class CacheUtils {
* @param cacheName * @param cacheName
* @return * @return
*/ */
private static Cache getCache(String cacheName){ /*private static Cache getCache(String cacheName){
Cache cache = cacheManager.getCache(cacheName); Cache cache = cacheManager.getCache(cacheName);
if (cache == null){ if (cache == null){
cacheManager.addCache(cacheName); cacheManager.addCache(cacheName);
@@ -88,9 +88,13 @@ public class CacheUtils {
cache.getCacheConfiguration().setEternal(true); cache.getCacheConfiguration().setEternal(true);
} }
return cache; return cache;
}*/
private static Cache getCache(String cacheName){
Cache cache = cacheManager.getCache(cacheName);
return cache;
} }
public static CacheManager getCacheManager() { public static RedisCacheManager getCacheManager() {
return cacheManager; return cacheManager;
} }

View File

@@ -1,12 +1,26 @@
package com.nis.web.controller.sys; package com.nis.web.controller.sys;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.derby.tools.sysinfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.crazycake.shiro.RedisCache;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ModelAttribute;
@@ -22,11 +36,15 @@ import com.nis.domain.Page;
import com.nis.domain.SysRole; import com.nis.domain.SysRole;
import com.nis.domain.SysUser; import com.nis.domain.SysUser;
import com.nis.util.DateUtils; import com.nis.util.DateUtils;
import com.nis.util.IpUtil;
import com.nis.util.StringUtil; import com.nis.util.StringUtil;
import com.nis.util.StringUtils; import com.nis.util.StringUtils;
import com.nis.util.excel.ExportExcel; import com.nis.util.excel.ExportExcel;
import com.nis.web.controller.BaseController; import com.nis.web.controller.BaseController;
import com.nis.web.security.SystemAuthorizingRealm;
import com.nis.web.security.SystemAuthorizingRealm.Principal;
import com.nis.web.security.UserUtils; import com.nis.web.security.UserUtils;
import com.nis.web.security.UsernamePasswordToken;
@Controller @Controller
@RequestMapping("${adminPath}/sys/user") @RequestMapping("${adminPath}/sys/user")
@@ -97,7 +115,7 @@ public class UserController extends BaseController{
return form(user, model); return form(user, model);
}*/ }*/
if (!"true".equals(checkLoginName(user.getOldLoginId(), user.getLoginId()))){ if (!"true".equals(checkLoginName(user.getOldLoginId(), user.getLoginId()))){
addMessage(redirectAttributes,"error", "save_failed"); addMessage(model,"error", "save_failed");
return form(user, model); return form(user, model);
} }
// 角色数据有效性验证,过滤不在授权内的角色 // 角色数据有效性验证,过滤不在授权内的角色
@@ -264,6 +282,7 @@ public class UserController extends BaseController{
/** /**
* 修改个人用户密码 * 修改个人用户密码
*
* @param oldPassword * @param oldPassword
* @param newPassword * @param newPassword
* @param model * @param model
@@ -274,9 +293,34 @@ public class UserController extends BaseController{
public String modifyPwd(String oldPassword, String newPassword, Model model) { public String modifyPwd(String oldPassword, String newPassword, Model model) {
SysUser user = UserUtils.getUser(); SysUser user = UserUtils.getUser();
if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) { if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
if (StringUtils.validatePassword(oldPassword, user.getPassword())) { if (StringUtils.validatePassword(oldPassword, user.getPassword())) {
userService.updatePasswordById(user.getId(), user.getLoginId(), newPassword); userService.updatePasswordById(user.getId(), user.getLoginId(), newPassword);
Session curSession = UserUtils.getSession();// 当前登录用户的session
Principal principal = UserUtils.getPrincipal();// 当前登录用户的鉴权信息
// 过滤 当前用户的 非此客户的其它登录信息
Collection<Session> allOtherSession = systemService.getActiveSessions(true, principal, curSession);
if (allOtherSession.size() > 0) {
// 如果是登录进来的,则踢出已在线用户
if (UserUtils.getSubject().isAuthenticated()) {
for (Session session : allOtherSession) {
systemService.deleteSession(session);
}
}
}
RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
Collection<Realm> realm = securityManager.getRealms();
for (Realm realm2 : realm) {
SystemAuthorizingRealm userRealm = (SystemAuthorizingRealm) realm2;
RedisCache<Object, AuthenticationInfo> cache = (RedisCache<Object, AuthenticationInfo>) userRealm.getAuthenticationCache();
String keyPrefix = cache.getKeyPrefix();
for (AuthenticationInfo auth : cache.values()) {
userRealm.getAuthenticationCache().remove(auth.getPrincipals().getPrimaryPrincipal());
}
systemService.deleteAuthenticationCache(keyPrefix + user.getName());
systemService.deleteAuthenticationCache(keyPrefix + user.getId());
}
model.addAttribute("message", "update_success"); model.addAttribute("message", "update_success");
} else { } else {
model.addAttribute("message", "update_failed"); model.addAttribute("message", "update_failed");
@@ -288,5 +332,4 @@ public class UserController extends BaseController{
} }

View File

@@ -11,6 +11,7 @@ import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext; import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -26,7 +27,8 @@ import com.nis.util.StringUtils;
* @author * @author
* @version * @version
*/ */
public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements SessionDAO { /*public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements SessionDAO {*/
public class CacheSessionDAO extends RedisSessionDAO {
private Logger logger = LoggerFactory.getLogger(getClass()); private Logger logger = LoggerFactory.getLogger(getClass());
@@ -34,7 +36,7 @@ public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements Sessio
super(); super();
} }
@Override /*@Override
protected void doUpdate(Session session) { protected void doUpdate(Session session) {
if (session == null || session.getId() == null) { if (session == null || session.getId() == null) {
return; return;
@@ -60,9 +62,9 @@ public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements Sessio
} }
super.doUpdate(session); super.doUpdate(session);
logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : ""); logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
} }*/
@Override /*@Override
protected void doDelete(Session session) { protected void doDelete(Session session) {
if (session == null || session.getId() == null) { if (session == null || session.getId() == null) {
return; return;
@@ -70,7 +72,7 @@ public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements Sessio
super.doDelete(session); super.doDelete(session);
logger.debug("delete {} ", session.getId()); logger.debug("delete {} ", session.getId());
} }*/
@Override @Override
protected Serializable doCreate(Session session) { protected Serializable doCreate(Session session) {
@@ -127,7 +129,6 @@ public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements Sessio
* @param includeLeave 是否包括离线最后访问时间大于3分钟为离线会话 * @param includeLeave 是否包括离线最后访问时间大于3分钟为离线会话
* @return * @return
*/ */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave) { public Collection<Session> getActiveSessions(boolean includeLeave) {
return getActiveSessions(includeLeave, null, null); return getActiveSessions(includeLeave, null, null);
} }
@@ -139,7 +140,6 @@ public class CacheSessionDAO extends EnterpriseCacheSessionDAO implements Sessio
* @param filterSession 不为空,则过滤掉(不包含)这个会话。 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return * @return
*/ */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) { public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
// 如果包括离线,并无登录者条件。 // 如果包括离线,并无登录者条件。
if (includeLeave && principal == null){ if (includeLeave && principal == null){

View File

@@ -1,31 +1,38 @@
package com.nis.web.security; package com.nis.web.security;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable; import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission; import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session; import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource; import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.google.code.kaptcha.Constants;
import com.nis.domain.SysMenu; import com.nis.domain.SysMenu;
import com.nis.domain.SysRole; import com.nis.domain.SysRole;
import com.nis.domain.SysUser; import com.nis.domain.SysUser;
@@ -34,8 +41,8 @@ import com.nis.util.Encodes;
import com.nis.util.LogUtils; import com.nis.util.LogUtils;
import com.nis.util.StringUtil; import com.nis.util.StringUtil;
import com.nis.util.StringUtils; import com.nis.util.StringUtils;
import com.nis.util.TreeUtil;
import com.nis.web.service.SystemService; import com.nis.web.service.SystemService;
import com.sun.jna.platform.win32.Netapi32Util.User;
/** /**
@@ -82,7 +89,8 @@ public class SystemAuthorizingRealm extends AuthorizingRealm {
throw new AuthenticationException("msg:该已帐号禁止登录."); throw new AuthenticationException("msg:该已帐号禁止登录.");
} }
byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16)); byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16));
return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()), user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName()); return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()), user.getPassword().substring(16), new MySimpleByteSource(salt), getName());
//return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()), user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
} }
return null; return null;
} }
@@ -194,14 +202,37 @@ public class SystemAuthorizingRealm extends AuthorizingRealm {
setCredentialsMatcher(matcher); setCredentialsMatcher(matcher);
} }
// /** /**
// * 清空用户关联权限认证,待下次使用时重新加载 * 清空用户关联权限认证,待下次使用时重新加载
// */ */
// public void clearCachedAuthorizationInfo(Principal principal) { public void clearCachedAuthorizationInfo(Principal principal) {
// SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
// clearCachedAuthorizationInfo(principals); clearCachedAuthorizationInfo(principals);
// } }
/**
* 清空用户关联权限认证,待下次使用时重新加载
*/
public void clearCachedAuthenticationInfo(Object principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthenticationInfo(principals);
}
/**
* 清空用户关联权限认证,待下次使用时重新加载
*/
public void clearCachedAuthorizationInfoC(PrincipalCollection principals) {
SimplePrincipalCollection principalsa = new SimplePrincipalCollection(principals, getName());
clearCachedAuthorizationInfo(principalsa);
}
/*@Override
protected void clearCachedAuthenticationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
super.clearCachedAuthenticationInfo(principals);
}
@Override
protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
super.clearCachedAuthorizationInfo(principals);
}*/
/** /**
* 授权用户信息 * 授权用户信息
@@ -293,3 +324,107 @@ public class SystemAuthorizingRealm extends AuthorizingRealm {
} }
} }
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);
}
}
}

View File

@@ -24,7 +24,12 @@ import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient; import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient; import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.session.Session; import org.apache.shiro.session.Session;
import org.crazycake.shiro.exception.SerializationException;
import org.crazycake.shiro.serializer.ObjectSerializer;
import org.crazycake.shiro.serializer.RedisSerializer;
import org.crazycake.shiro.serializer.StringSerializer;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -39,15 +44,19 @@ import com.nis.util.TimeConstants;
import com.nis.web.dao.SrcIpDao; import com.nis.web.dao.SrcIpDao;
import com.nis.web.dao.SysOfficeDao; import com.nis.web.dao.SysOfficeDao;
import com.nis.web.dao.UserDao; import com.nis.web.dao.UserDao;
import com.nis.web.security.CacheSessionDAO;
import com.nis.web.security.Servlets; import com.nis.web.security.Servlets;
import com.nis.web.security.SessionDAO; import com.nis.web.security.SessionDAO;
import com.nis.web.security.UserUtils; import com.nis.web.security.UserUtils;
import antlr.StringUtils;
@Service @Service
public class SystemService extends BaseService{ public class SystemService extends BaseService{
@Autowired @Autowired
private SessionDAO sessionDao; private CacheSessionDAO sessionDao;
/*private SessionDAO sessionDao;*/
@Autowired @Autowired
private UserDao userDao; private UserDao userDao;
@@ -57,7 +66,8 @@ public class SystemService extends BaseService{
@Autowired @Autowired
private SrcIpDao srcIpDao; private SrcIpDao srcIpDao;
private RedisSerializer keySerializer = new StringSerializer();
private RedisSerializer valueSerializer = new ObjectSerializer();
public Collection<Session> getActiveSessions(boolean includeLeave) { public Collection<Session> getActiveSessions(boolean includeLeave) {
return sessionDao.getActiveSessions(includeLeave); return sessionDao.getActiveSessions(includeLeave);
@@ -72,6 +82,17 @@ public class SystemService extends BaseService{
sessionDao.delete(session); sessionDao.delete(session);
} }
public void deleteAuthenticationCache(String authenticationInfo) {
if (org.apache.commons.lang3.StringUtils.isBlank(authenticationInfo)) {
logger.error("AuthenticationInfo is null");
return;
}
try {
sessionDao.getRedisManager().del(keySerializer.serialize(authenticationInfo));
} catch (SerializationException e) {
logger.error("delete AuthenticationInfo error. AuthenticationInfo key=" + authenticationInfo);
}
}
public SysUser getUserByLoginName(String loginName) { public SysUser getUserByLoginName(String loginName) {
return UserUtils.getByLoginName(loginName); return UserUtils.getByLoginName(loginName);

View File

@@ -77,14 +77,25 @@
<!-- 定义Shiro安全管理配置 --> <!-- 定义Shiro安全管理配置 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="systemAuthorizingRealm" /> <!-- <property name="realm" ref="systemAuthorizingRealm" /> -->
<property name="realm" ref="shiroRealm" />
<property name="sessionManager" ref="sessionManager" /> <property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="shiroCacheManager" /> <property name="cacheManager" ref="shiroCacheManager" />
</bean> </bean>
<bean id="shiroRealm" class="com.nis.web.security.SystemAuthorizingRealm">
<!-- 启用缓存 -->
<property name="cachingEnabled" value="true"></property>
<!-- 启用身份验证缓存 -->
<property name="authenticationCachingEnabled" value="true"></property>
<!-- 启用授权缓存 -->
<property name="authorizationCachingEnabled" value="true"></property>
</bean>
<!-- 自定义会话管理配置 --> <!-- 自定义会话管理配置 -->
<bean id="sessionManager" class="com.nis.web.security.SessionManager"> <bean id="sessionManager" class="com.nis.web.security.SessionManager">
<property name="sessionDAO" ref="sessionDAO"/> <!-- <property name="sessionDAO" ref="sessionDAO"/> -->
<property name="sessionDAO" ref="redisSessionDAO"/>
<!-- 会话超时时间,单位:毫秒 --> <!-- 会话超时时间,单位:毫秒 -->
<property name="globalSessionTimeout" value="${session.sessionTimeout}"/> <property name="globalSessionTimeout" value="${session.sessionTimeout}"/>
@@ -98,22 +109,35 @@
<property name="sessionIdCookieEnabled" value="true"/> <property name="sessionIdCookieEnabled" value="true"/>
</bean> </bean>
<bean id="redisSessionDAO" class="com.nis.web.security.CacheSessionDAO">
<property name="expire" value="${redis.expire}"></property>
<property name="redisManager" ref="redisManager"></property>
<property name="keyPrefix" value="shiro_redis_"></property>
</bean>
<!-- 指定本系统SESSIONID, 默认为: JSESSIONID 问题: 与SERVLET容器名冲突, 如JETTY, TOMCAT 等默认JSESSIONID, <!-- 指定本系统SESSIONID, 默认为: JSESSIONID 问题: 与SERVLET容器名冲突, 如JETTY, TOMCAT 等默认JSESSIONID,
当跳出SHIRO SERVLET时如ERROR-PAGE容器会为JSESSIONID重新分配值导致登录会话丢失! --> 当跳出SHIRO SERVLET时如ERROR-PAGE容器会为JSESSIONID重新分配值导致登录会话丢失! -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg name="name" value="nis.session.id"/> <constructor-arg name="name" value="nis.session.id"/>
</bean> </bean>
<bean id="sessionDAO" class="com.nis.web.security.CacheSessionDAO"> <!-- <bean id="sessionDAO" class="com.nis.web.security.CacheSessionDAO">
<property name="sessionIdGenerator" ref="idGen" /> <property name="sessionIdGenerator" ref="idGen" />
<property name="activeSessionsCacheName" value="activeSessionsCache" /> <property name="activeSessionsCacheName" value="activeSessionsCache" />
<property name="cacheManager" ref="shiroCacheManager" /> <property name="cacheManager" ref="shiroCacheManager" />
</bean> </bean> -->
<!-- 定义授权缓存管理器 --> <!-- 定义授权缓存管理器 -->
<!-- <bean id="shiroCacheManager" class="com.thinkgem.jeesite.common.security.shiro.cache.SessionCacheManager" /> --> <!-- <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="cacheManager"/> <property name="cacheManager" ref="cacheManager"/>
</bean> -->
<bean id="shiroCacheManager" class="org.crazycake.shiro.RedisCacheManager">
<property name="redisManager" ref="redisManager"/>
</bean>
<bean id="redisManager" class="org.crazycake.shiro.RedisManager">
<property name="host" value="${redis.host}"></property>
<property name="timeout" value="${redis.timeout}"></property>
</bean> </bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 --> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->

View File

@@ -1132,7 +1132,7 @@ report_total=Total
message_type=Message Type message_type=Message Type
as=AS as=AS
route=Route route=Route
transport_layer_protocol=TLS Protocol transport_layer_protocol=Protocol
av_voip_monit=VoIP Monitor av_voip_monit=VoIP Monitor
av_voip_reject=VoIP Block av_voip_reject=VoIP Block
label_proto_source=Protocol Source label_proto_source=Protocol Source
@@ -1158,7 +1158,7 @@ traffic_ipactive_hour_trend=Active IP TOP10 Trend In Nearly One Hour
traffic_ipactive_hour_max=Active IP TOP10 Maximum In Nearly One Hour traffic_ipactive_hour_max=Active IP TOP10 Maximum In Nearly One Hour
ip_addr=IP ip_addr=IP
area_id=Area area_id=Area
link_num=Link Number link_num=Link Times
stat_time=Statistical Time stat_time=Statistical Time
log_menu=Operation Menu log_menu=Operation Menu
log_management=Log Management log_management=Log Management

View File

@@ -1132,7 +1132,7 @@ report_total=\u0412\u0441\u0435\u0433\u043E
message_type=\u0422\u0438\u043F \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F message_type=\u0422\u0438\u043F \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F
as=\u041A\u0410\u041A as=\u041A\u0410\u041A
route=\u041C\u0430\u0440\u0448\u0440\u0443\u0442 route=\u041C\u0430\u0440\u0448\u0440\u0443\u0442
transport_layer_protocol=\u041F\u0440\u043E\u0442\u043E\u043A\u043E\u043B TLS transport_layer_protocol=\u041F\u0440\u043E\u0442\u043E\u043A\u043E\u043B
av_voip_monit=\u041C\u043E\u043D\u0438\u0442\u043E\u0440\u0438\u043D\u0433 VoIP av_voip_monit=\u041C\u043E\u043D\u0438\u0442\u043E\u0440\u0438\u043D\u0433 VoIP
av_voip_reject=VoIP \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 av_voip_reject=VoIP \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435
label_proto_source=\u0418\u0441\u0442\u043E\u0447\u043D\u0438\u043A \u043F\u0440\u043E\u0442\u043E\u043A\u043E\u043B\u0430 label_proto_source=\u0418\u0441\u0442\u043E\u0447\u043D\u0438\u043A \u043F\u0440\u043E\u0442\u043E\u043A\u043E\u043B\u0430
@@ -1158,7 +1158,7 @@ traffic_ipactive_hour_trend=\u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0439 IP
traffic_ipactive_hour_max=\u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0439 IP TOP10 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C \u0437\u0430 \u043E\u0434\u0438\u043D \u0447\u0430\u0441 traffic_ipactive_hour_max=\u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0439 IP TOP10 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C \u0437\u0430 \u043E\u0434\u0438\u043D \u0447\u0430\u0441
ip_addr=IP ip_addr=IP
area_id=\u0420\u0435\u0433\u0438\u043E\u043D area_id=\u0420\u0435\u0433\u0438\u043E\u043D
link_num=\u041D\u043E\u043C\u0435\u0440 \u0441\u0441\u044B\u043B\u043A\u0438 link_num=\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0439
stat_time=\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u0432\u0440\u0435\u043C\u044F stat_time=\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u0432\u0440\u0435\u043C\u044F
log_menu=\u041C\u0435\u043D\u044E \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439 log_menu=\u041C\u0435\u043D\u044E \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439
log_management=\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0436\u0443\u0440\u043D\u0430\u043B\u043E\u043C log_management=\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0436\u0443\u0440\u043D\u0430\u043B\u043E\u043C

View File

@@ -577,7 +577,7 @@ trafficBandwidthTrans=trafficBandwidthTrans
trafficProtocolList=trafficProtocolList trafficProtocolList=trafficProtocolList
trafficAppList=trafficAppList trafficAppList=trafficAppList
ntcActionEntranceReport=ntcActionEntranceReport ntcActionEntranceReport=ntcActionEntranceReport
redis.host=10.0.4.1:6379 redis.host=192.168.10.192:6379
redis.expire=1800 redis.expire=1800
redis.timeout=10000 redis.timeout=10000
dns_spoofing_ip_desc=Default Spoofing IP dns_spoofing_ip_desc=Default Spoofing IP