org.apache.shiro.subject.support.DefaultSubjectContext Java Examples

The following examples show how to use org.apache.shiro.subject.support.DefaultSubjectContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SessionEvaluator.java    From jqm with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSessionStorageEnabled(Subject subject)
{
    // If disabled in request (e.g. by using the noSessionCreation filter, it stays disabled.
    if (WebUtils.isWeb(subject))
    {
        HttpServletRequest request = WebUtils.getHttpRequest(subject);
        Object o = request.getAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED);
        if (o != null && !((Boolean) o))
        {
            return false;
        }
    }

    // Then only allow humans, not API-only users, to create a session
    if (subject.hasRole("human"))
    {
        return true;
    }

    // By default, no sessions allowed.
    return false;
}
 
Example #2
Source File: UserAdminManagerController.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
@RequestMapping("admin/userManager/userOnlineStore")
public void getOnlineUsers(Model model) {
	Iterator<Session> sessions = sessionDao.getActiveSessions().iterator();
	ArrayList<OnlineUser> ous = new ArrayList<OnlineUser>();
	while (sessions.hasNext()) {
		OnlineUser ou = new OnlineUser();
		SimpleSession session = (SimpleSession) sessions.next();
		ou.setHost(session.getHost());
		ou.setId(session.getId().toString());
		ou.setLastAccessTime(session.getLastAccessTime());
		ou.setStartTime(session.getStartTimestamp());
		PrincipalCollection principal = (PrincipalCollection) session
				.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		if (principal != null) {
			ShiroUser su = (ShiroUser) principal.getPrimaryPrincipal();
			ou.setUserid(su.loginName);
			ou.setUsername(su.name);
			ou.setLogin(true);
		}
		ous.add(ou);
	}
	model.addAttribute("users", ous);
	model.addAttribute("total", ous.size());
}
 
Example #3
Source File: UserNameRealm.java    From Shiro-Action with MIT License 6 votes vote down vote up
public void clearAuthCacheByUserId(Integer userId) {
    // 获取所有 session
    Collection<Session> sessions = sessionDAO.getActiveSessions();
    for (Session session : sessions) {
        // 获取 session 登录信息。
        Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (obj instanceof SimplePrincipalCollection) {
            // 强转
            SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
            User user = new User();
            BeanUtils.copyProperties(spc.getPrimaryPrincipal(), user);
            // 判断用户, 匹配用户ID.
            if (userId.equals(user.getUserId())) {
                this.doClearCache(spc);
            }
        }
    }
}
 
Example #4
Source File: UserOnlineServiceImpl.java    From belling-admin with Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasLogin(String account) {
	try {
		if (Strings.isNullOrEmpty(account)) return true;
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		for(Session session : sessions){
			Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (null != obj) {
				if (account.equals(obj.toString()) && session.getAttribute("kickout") == null) {
					return true;
				}
			}
		}
	} catch(Exception ex) {
		ex.printStackTrace();
	}
	return false;
}
 
Example #5
Source File: UserOnlineServiceImpl.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void kickoutByAccount(String account) {
	if (Strings.isNullOrEmpty(account)) return;
	Collection<Session> sessions = sessionDAO.getActiveSessions();
	if (sessions.size() <= 0) return;
	System.out.println("kickoutByAccount sessions size is :" + sessions.size());
	for(Session session : sessions){
		Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		if (obj != null) {
			String tempName = obj.toString();
			if (account.equals(tempName)) {
				// 会话已失效  但在线列表仍可获取Session会话对象
				session.setAttribute("kickout", true); // 标记为已下线
				session.setTimeout(0L); //设置session立即失效,即将其踢出系统break;
				// session.stop(); //销毁Shiro的会话
				
				// 记录日志
				LoginLog log = new LoginLog();
				log.setUserId(account);
				log.setLoginType((short) 1);
				log.setLoginDesc("账号异地登录,被迫强制下线");
				log.setIpInfoCountry(null);
				log.setIpInfoRegion(null);
				log.setIpInfoCity(null);
				log.setIpInfoIsp(null);
				log.setLoginIp(RequestUtil.getAddr(RequestUtil.getRequest()));
				log.setLoginTime(new Timestamp(new Date().getTime()));
				
				// 保存退出日志
				loginLogMapper.insert(log);
				break;
			}
		}
	}
}
 
Example #6
Source File: ShiroSecurityHelper.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
public Session getSessionByUsername(String username){
	Collection<Session> sessions = getSessionDAO().getActiveSessions();
	for(Session session : sessions){
		if(null != session && StringUtils.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)), username)){
			return session;
		}
	}
	
	return null;
}
 
Example #7
Source File: NexusBasicHttpAuthenticationFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Disable session creation for all BASIC auth requests.
 */
@Override
public boolean onPreHandle(final ServletRequest request, final ServletResponse response, final Object mappedValue)
    throws Exception
{
  // Basic auth should never create sessions; we do not want session overhead for non-user clients that supply
  // credentials
  request.setAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED, Boolean.FALSE);

  return super.onPreHandle(request, response, mappedValue);
}
 
Example #8
Source File: CacheSessionDAO.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 获取活动会话
 * @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
 * @param principal 根据登录者对象获取活动会话
 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
	// 如果包括离线,并无登录者条件。
	if (includeLeave && principal == null){
		return getActiveSessions();
	}
	Set<Session> sessions = Sets.newHashSet();
	for (Session session : getActiveSessions()){
		boolean isActiveSession = false;
		// 不包括离线并符合最后访问时间小于等于3分钟条件。
		if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
			isActiveSession = true;
		}
		// 符合登陆者条件。
		if (principal != null){
			PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
				isActiveSession = true;
			}
		}
		// 过滤掉的SESSION
		if (filterSession != null && filterSession.getId().equals(session.getId())){
			isActiveSession = false;
		}
		if (isActiveSession){
			sessions.add(session);
		}
	}
	return sessions;
}
 
Example #9
Source File: CacheSessionDAO.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
 * 获取活动会话
 * @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
 * @param principal 根据登录者对象获取活动会话
 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
	// 如果包括离线,并无登录者条件。
	if (includeLeave && principal == null){
		return getActiveSessions();
	}
	Set<Session> sessions = Sets.newHashSet();
	for (Session session : getActiveSessions()){
		boolean isActiveSession = false;
		// 不包括离线并符合最后访问时间小于等于3分钟条件。
		if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
			isActiveSession = true;
		}
		// 符合登陆者条件。
		if (principal != null){
			PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
				isActiveSession = true;
			}
		}
		// 过滤掉的SESSION
		if (filterSession != null && filterSession.getId().equals(session.getId())){
			isActiveSession = false;
		}
		if (isActiveSession){
			sessions.add(session);
		}
	}
	return sessions;
}
 
Example #10
Source File: ShiroSessionDao.java    From Spring-Shiro-Spark with Apache License 2.0 5 votes vote down vote up
/**
 * 如果session中没有登录信息就调用doReadSession方法从Redis中重读
 * session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null 代表没有登录,登录后Shiro会放入该值
 * @param sessionId
 * @return
 * @throws UnknownSessionException
 */
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException{
    Session session = getCachedSession(sessionId);
    if(session == null || session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
        session =  this.doReadSession(sessionId);
        if(session == null){
            throw new UnknownSessionException("There is no session with id [" + sessionId + "]");
        }else {
            cache(session,session.getId());
        }
    }
    return session;
}
 
Example #11
Source File: UserOnlineServiceImpl.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
/**
 * 从session中获取UserOnline对象
 * 
 * @param session
 * @return
 */
private UserOnlineDTO getSessionDTO(Session session){
	if (null == session) {
		return null;
	}
	Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
	if (null == obj) {
		return null;
	}
	//存储session
	UserOnlineDTO userDto = new UserOnlineDTO();
	// 登录账号
	userDto.setLoginAccount(obj.toString());
	//最后一次和系统交互的时间
	userDto.setLastAccess(session.getLastAccessTime());
	// 开始时间
	userDto.setStartTime(session.getStartTimestamp());
	//主机的ip地址
	userDto.setIp(session.getHost());
	//session ID
	userDto.setSessionId(session.getId().toString());
	//回话到期 ttl(ms)
	userDto.setTimeout(session.getTimeout());
	//session创建时间
	userDto.setStartTime(session.getStartTimestamp());
	return userDto;
}
 
Example #12
Source File: UserService.java    From Shiro-Action with MIT License 5 votes vote down vote up
/**
 * 删除所有此用户的在线用户
 */
public void offlineByUserId(Integer userId) {
    Collection<Session> activeSessions = sessionDAO.getActiveSessions();
    for (Session session : activeSessions) {
        SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (simplePrincipalCollection != null) {
            User user = (User) simplePrincipalCollection.getPrimaryPrincipal();
            if (user != null && userId.equals(user.getUserId())) {
                offlineBySessionId(String.valueOf(session.getId()));
            }
        }
    }
}
 
Example #13
Source File: UserNameRealm.java    From Shiro-Action with MIT License 5 votes vote down vote up
public void clearAllAuthCache() {
    // 获取所有 session
    Collection<Session> sessions = sessionDAO.getActiveSessions();
    for (Session session : sessions) {
        // 获取 session 登录信息。
        Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (obj instanceof SimplePrincipalCollection) {
            // 强转
            SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
            User user = new User();
            BeanUtils.copyProperties(spc.getPrimaryPrincipal(), user);
            this.doClearCache(spc);
        }
    }
}
 
Example #14
Source File: TestBindClientContextHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindByAuthHeader() throws Exception {
   SimpleSession session = new SimpleSession();
   session.setId("test");
   session.setExpired(false);
   session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, true);
   
   EasyMock
      .expect(sessionDao.readSession("test"))
      .andReturn(session)
      // FIXME why does shiro load the session so many times????
      .anyTimes();
   
   sessionDao.update(session);
   EasyMock
      .expectLastCall()
      .times(1);
   
   replay();

   DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/client");
   DefaultHttpHeaders.addHeader(request, "Authorization", "test");
   handler.channelRead(context, request);
   
   
   // an authenticated Client should have been bound
   ClientFactory factory = ServiceLocator.getInstance(ClientFactory.class);
   Client client = factory.get(channel);
   assertNotNull(client);
   assertTrue(client.isAuthenticated());
   assertEquals("test", client.getSessionId());

   verify();
}
 
Example #15
Source File: TestBindClientContextHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindByCookie() throws Exception {
   SimpleSession session = new SimpleSession();
   session.setId("test");
   session.setExpired(false);
   session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, true);
   
   EasyMock
      .expect(sessionDao.readSession("test"))
      .andReturn(session)
      // FIXME why does shiro load the session so many times????
      .anyTimes();
   
   sessionDao.update(session);
   EasyMock
      .expectLastCall()
      .times(1);
   
   replay();

   DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/client");
   DefaultHttpHeaders.addHeader(request, "Cookie", "irisAuthToken=test;");
   handler.channelRead(context, request);
   
   
   // an authenticated Client should have been bound
   ClientFactory factory = ServiceLocator.getInstance(ClientFactory.class);
   Client client = factory.get(channel);
   assertNotNull(client);
   assertTrue(client.isAuthenticated());
   assertEquals("test", client.getSessionId());

   verify();
}
 
Example #16
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Object deserializeAttribute(String key, String json) {
	if (key.equals(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY)) {
		return gson.fromJson(json, Boolean.class);
	}
	if (key.equals(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)) {
		return gson.fromJson(json, SimplePrincipalCollection.class);
	}
	logger.error("Unknown key: {}. Unable to deserialize value: {}", key, json);
	return null;
}
 
Example #17
Source File: CacheSessionDAO.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 获取活动会话
 * @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
 * @param principal 根据登录者对象获取活动会话
 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
	// 如果包括离线,并无登录者条件。
	if (includeLeave && principal == null){
		return getActiveSessions();
	}
	Set<Session> sessions = Sets.newHashSet();
	for (Session session : getActiveSessions()){
		boolean isActiveSession = false;
		// 不包括离线并符合最后访问时间小于等于3分钟条件。
		if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
			isActiveSession = true;
		}
		// 符合登陆者条件。
		if (principal != null){
			PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
				isActiveSession = true;
			}
		}
		// 过滤掉的SESSION
		if (filterSession != null && filterSession.getId().equals(session.getId())){
			isActiveSession = false;
		}
		if (isActiveSession){
			sessions.add(session);
		}
	}
	return sessions;
}
 
Example #18
Source File: OnlineController.java    From frpMgr with MIT License 4 votes vote down vote up
/**
 * 在线用户列表数据
 * @param request
 * @param response
 * @author ThinkGem
 */
@RequiresPermissions("sys:online:view")
@RequestMapping(value = "listData")
@ResponseBody
public List<Map<String, Object>> listData(String isAllOnline, String isVisitor, String sessionId, 
		String userCode, String userName, String userType, String orderBy) {
	List<Map<String, Object>> list = Lists.newArrayList();
	boolean excludeLeave = isAllOnline==null || !Global.YES.equals(isAllOnline);
	boolean excludeVisitor = isVisitor==null || !Global.YES.equals(isVisitor);
		Collection<Session> sessions = sessionDAO.getActiveSessions(excludeLeave, 
			excludeVisitor, null, sessionId, userCode);
	long currentTime = System.currentTimeMillis();
	for (Session session : sessions){
		if (StringUtils.isNotBlank(userName) && ((String)session.getAttribute("userName")).contains(userName)){
			continue;
		}
		if (StringUtils.isNotBlank(userType) && ((String)session.getAttribute("userType")).equals(userType)){
			continue;
		}
		Map<String, Object> map = Maps.newLinkedHashMap();
		// 为了安全性,需要有权限的人才能看
		if (UserUtils.getSubject().isPermitted("sys:online:edit")){
			map.put("id", session.getId().toString()); 
		}
		map.put("startTimestamp", DateUtils.formatDateTime(session.getStartTimestamp()));
		map.put("lastAccessTime", DateUtils.formatDateTime(session.getLastAccessTime()));
		map.put("timeout", TimeUtils.formatDateAgo(session.getTimeout()-(currentTime-session.getLastAccessTime().getTime())));
		PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		LoginInfo principal = (pc != null ? (LoginInfo)pc.getPrimaryPrincipal() : null);
		if (principal != null){
			map.put("userCode", session.getAttribute("userCode"));// principal.getId());
			map.put("userName", session.getAttribute("userName"));// principal.getName());
			map.put("userType", session.getAttribute("userType"));// ObjectUtils.toString(principal.getParam("userType")));
			map.put("deviceType", ObjectUtils.toString(principal.getParam("deviceType")));
		}
		map.put("host", session.getHost());
		list.add(map);
	}
	// 本地排序
	if (StringUtils.isNotBlank(orderBy)){
		final String[] ss = orderBy.trim().split(" ");
		if (ss != null && ss.length == 2){
			Collections.sort(list, new Comparator<Map<String, Object>>() {
				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					String s1 = (String)o1.get(ss[0]);
					String s2 = (String)o2.get(ss[0]);
					if ("asc".equals(ss[1])){
						return s1.compareTo(s2);
					}else{
						return s2.compareTo(s1);
					}
				}});
		}
	}
	return list;
}
 
Example #19
Source File: JedisSessionDAO.java    From easyweb with Apache License 2.0 4 votes vote down vote up
@Override
public void update(Session session) throws UnknownSessionException {
	if (session == null || session.getId() == null) {  
           return;
       }
	
	HttpServletRequest request = Servlets.getRequest();
	if (request != null){
		String uri = request.getServletPath();
		// 如果是静态文件,则不更新SESSION
		if (Servlets.isStaticFile(uri)){
			return;
		}
		// 如果是视图文件,则不更新SESSION
		if (StringUtils.startsWith(uri, Global.getInstance().getConfig("app.view.prefix"))
				&& StringUtils.endsWith(uri, Global.getInstance().getConfig("app.view.suffix"))){
			return;
		}
		// 手动控制不更新SESSION
		if (Global.NO.equals(request.getParameter("updateSession"))){
			return;
		}
	}
	
	Jedis jedis = null;
	try {
		
		jedis = JedisUtils.getResource();
		
		// 获取登录者编号
		PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;
		
		jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
		jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));
		
		// 设置超期时间
		int timeoutSeconds = (int)(session.getTimeout() / 1000);
		jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);

		logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
	} catch (Exception e) {
		logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
	} finally {
		JedisUtils.returnResource(jedis);
	}
}
 
Example #20
Source File: JedisSessionDAO.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
@Override
public void update(Session session) throws UnknownSessionException {
	if (session == null || session.getId() == null) {  
           return;
       }
	
	HttpServletRequest request = Servlets.getRequest();
	if (request != null){
		String uri = request.getServletPath();
		// 如果是静态文件,则不更新SESSION
		if (Servlets.isStaticFile(uri)){
			return;
		}
		// 如果是视图文件,则不更新SESSION
		if (StringUtils.startsWith(uri, Global.getConfig("web.view.prefix"))
				&& StringUtils.endsWith(uri, Global.getConfig("web.view.suffix"))){
			return;
		}
		// 手动控制不更新SESSION
		if (Global.NO.equals(request.getParameter("updateSession"))){
			return;
		}
	}
	
	Jedis jedis = null;
	try {
		
		jedis = JedisUtils.getResource();
		
		// 获取登录者编号
		PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;
		
		jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
		jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));
		
		// 设置超期时间
		int timeoutSeconds = (int)(session.getTimeout() / 1000);
		jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);

		logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
	} catch (Exception e) {
		logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
	} finally {
		JedisUtils.returnResource(jedis);
	}
}
 
Example #21
Source File: JedisSessionDAO.java    From NutzSite with Apache License 2.0 4 votes vote down vote up
@Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            return;
        }

        HttpServletRequest request = Mvcs.getReq();
        if (request != null){
            String uri = request.getServletPath();
            // 如果是静态文件,则不更新SESSION
            if (isStaticFile(uri)){
                return;
            }

            // 手动控制不更新SESSION
//            if (Global.NO.equals(request.getParameter("updateSession"))){
//                return;
//            }
        }

        Jedis jedis = null;
        try {

            jedis = jedisAgent.getResource();

            // 获取登录者编号
            PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;

            jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
            jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));

            // 设置超期时间
            int timeoutSeconds = (int)(session.getTimeout() / 1000);
            jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);

            logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
        } catch (Exception e) {
            logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
        } finally {
           Streams.safeClose(jedis);
        }
    }