Example usage for org.apache.shiro.subject.support DefaultSubjectContext PRINCIPALS_SESSION_KEY

List of usage examples for org.apache.shiro.subject.support DefaultSubjectContext PRINCIPALS_SESSION_KEY

Introduction

In this page you can find the example usage for org.apache.shiro.subject.support DefaultSubjectContext PRINCIPALS_SESSION_KEY.

Prototype

String PRINCIPALS_SESSION_KEY

To view the source code for org.apache.shiro.subject.support DefaultSubjectContext PRINCIPALS_SESSION_KEY.

Click Source Link

Document

The session key that is used to store subject principals.

Usage

From source file:com.funtl.framework.apache.shiro.session.CacheSessionDAO.java

License:Apache License

/**
 * ??/*  www  . j  ava  2s .  com*/
 *
 * @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;
}

From source file:com.funtl.framework.apache.shiro.session.JedisSessionDAO.java

License:Apache License

@Override
public void update(Session session) throws UnknownSessionException {
    if (session == null || session.getId() == null) {
        return;/*from w ww. ja  v  a 2 s  .c o m*/
    }

    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);
    }
}

From source file:com.funtl.framework.apache.shiro.session.JedisSessionDAO.java

License:Apache License

/**
 * ??/*from   w  ww.  j  a v  a2 s .  c  o m*/
 *
 * @param includeLeave  ??3?
 * @param principal     ???
 * @param filterSession ????
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
    Set<Session> sessions = Sets.newHashSet();

    Jedis jedis = null;
    try {
        jedis = JedisUtils.getResource();
        Map<String, String> map = jedis.hgetAll(sessionKeyPrefix);
        for (Map.Entry<String, String> e : map.entrySet()) {
            if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())) {

                String[] ss = StringUtils.split(e.getValue(), "|");
                if (ss != null && ss.length == 3) {// jedis.exists(sessionKeyPrefix + e.getKey())){
                    // Session session = (Session)JedisUtils.toObject(jedis.get(JedisUtils.getBytesKey(sessionKeyPrefix + e.getKey())));
                    SimpleSession session = new SimpleSession();
                    session.setId(e.getKey());
                    session.setAttribute("principalId", ss[0]);
                    session.setTimeout(Long.valueOf(ss[1]));
                    session.setLastAccessTime(new Date(Long.valueOf(ss[2])));
                    try {
                        // ?SESSION
                        session.validate();

                        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);
                        }

                    }
                    // SESSION?
                    catch (Exception e2) {
                        jedis.hdel(sessionKeyPrefix, e.getKey());
                    }
                }
                // SESSION??
                else {
                    jedis.hdel(sessionKeyPrefix, e.getKey());
                }
            }
            // SESSIONValue
            else if (StringUtils.isNotBlank(e.getKey())) {
                jedis.hdel(sessionKeyPrefix, e.getKey());
            }
        }
        logger.info("getActiveSessions size: {} ", sessions.size());
    } catch (Exception e) {
        logger.error("getActiveSessions", e);
    } finally {
        JedisUtils.returnResource(jedis);
    }
    return sessions;
}

From source file:com.ineunet.knife.security.Server.java

License:Apache License

/**
 * @param session/*from  w w w  . j  ava  2s  .  c o  m*/
 * @since 1.2.1
 */
public static void logout(Session session) {
    session.removeAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
    session.removeAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
}

From source file:com.wms.studio.controller.admin.UserAdminManagerController.java

License:Apache License

@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());//from  ww w.j  av  a 2  s . c om
        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());
}

From source file:com.zht.common.shiro.filter.MaxSessionControlFororRedisFilter.java

License:Apache License

@Override
protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    if (!subject.isAuthenticated() && !subject.isRemembered()) {
        // ??//w w  w  .  ja v  a2 s  .  c  o  m
        WebUtils.redirectToSavedRequest(request, response, loginFaildUrl);
        ;
    }
    Session newLonginSession = subject.getSession();
    String username = (String) subject.getPrincipal();
    Serializable newLonginSessionId = newLonginSession.getId();

    Collection<Session> activeSessions = shiroSessionDAO.getActiveSessions();
    if (activeSessions != null && activeSessions.size() > 0) {
        for (Session session : activeSessions) {
            if (null != session && ZStrUtil.equals(
                    String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)),
                    username)) {
                if (!session.getId().equals(newLonginSessionId)) {
                    shiroSessionDAO.delete(session);
                }
            }

        }
    }

    super.postHandle(request, response);
}

From source file:com.zht.common.shiro.util.ShiroSecurityHelper.java

License:Apache License

public static Session getSessionByUsername(String username) {

    Collection<Session> sessions = sessionDAO.getActiveSessions();
    for (Session session : sessions) {
        if (null != session && ZStrUtil.equals(
                String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)), username)) {
            return session;
        }/*from w  w  w . j  a  v  a2  s  .  c o  m*/
    }
    return null;
}

From source file:org.frat.common.security.BaseSecurityContext.java

License:Open Source License

/**
 * @param username//  ww w .j  a  va  2 s  .  c  o m
 * @return
 */
public static HashSet<HttpSession> getSessionByUsername(String username) {

    @SuppressWarnings("unchecked")
    HashSet<HttpSession> sessions = (HashSet<HttpSession>) WebUtil.getThreadSession().getServletContext()
            .getAttribute("loginSessions");
    HashSet<HttpSession> httpSessions = new HashSet<HttpSession>();
    for (HttpSession session : sessions) {
        if (null != session && StringUtil.isEqualObj(
                String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)), username)) {
            httpSessions.add(session);
        }
    }
    return httpSessions;
}

From source file:org.frat.common.security.BaseSecurityContext.java

License:Open Source License

/**
 * .//www. j  a v  a2  s.com
 * 
 * @param username
 */
public static void kickOutUser(String username) {
    try {
        // applicationHashSet?session
        @SuppressWarnings("unchecked")
        HashSet<HttpSession> sessions = (HashSet<HttpSession>) WebUtil.getServletContext()
                .getAttribute("loginSessions");
        List<HttpSession> sessionList = new ArrayList<HttpSession>();
        for (HttpSession session : sessions) {
            if (null != session && StringUtil.isEqualObj(
                    String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)),
                    username)) {
                // session
                if (!StringUtil.isEqualObj(session.getId(), WebUtil.getSessionId())) {
                    sessionList.add(session);
                }
            }
        }
        for (HttpSession session : sessionList) {
            session.invalidate();
            LOGGER.info("success kick out session [" + session.getId() + "]");
            LOGGER.info("success kick out user [" + username + "]");
        }
    } catch (Exception e) {
        LOGGER.error("");
        LOGGER.error(StackTraceUtil.getStackTrace(e));
    }
}

From source file:org.graylog2.security.MongoDbSession.java

License:Open Source License

public Optional<String> getUsernameAttribute() {
    final Map<Object, Object> attributes = getAttributes();
    if (attributes == null) {
        return Optional.empty();
    }// ww  w .  j ava  2 s  . c o m
    return Optional.ofNullable(String.valueOf(attributes.get(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)));
}