Java Code Examples for org.apache.shiro.session.Session#setTimeout()

The following examples show how to use org.apache.shiro.session.Session#setTimeout() . 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: ShiroSessionDao.java    From Spring-Shiro-Spark with Apache License 2.0 6 votes vote down vote up
/**
 * SessionManager创建完session后会调用该方法
 * @param session
 * @return
 */
@Override
protected Serializable doCreate(Session session) {
    Serializable sessionId = this.generateSessionId(session);
    assignSessionId(session,sessionId);
    Jedis jedis = null;
    try{
        jedis = jedisPool.getResource();
        //session由Redis缓存失效决定,这里作简单标识
        session.setTimeout(expireTime);
        jedis.setex(prefix + sessionId, expireTime, SerializeUtils.serializaToString((ShiroSession) session));
        logger.info("sessionId {} name {} 被创建", sessionId, session.getClass().getName());
    }catch (Exception e){
        logger.warn("创建session失败",e);
    }finally {
        jedis.close();
    }
    return sessionId;
}
 
Example 2
Source File: RedisSessionDAO.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * save session
 * @param session
 * @throws UnknownSessionException
 */
private void saveSession(Session session) throws UnknownSessionException{
    if(session == null || session.getId() == null){
        logger.error("session or session id is null");
        return;
    }
    
    byte[] key = getByteKey(session.getId());
    byte[] value = JavaSerializeUtil.serialize(session);
    session.setTimeout(expire*1000);
    try {
        this.jedisClient.set(key, value, expire);
    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 3
Source File: MyRealm.java    From demo-springmvc-shiro with Apache License 2.0 5 votes vote down vote up
/**
 * 将一些数据放到ShiroSession中,以便于其它地方使用
 * 比如Controller里面,使用时直接用HttpSession.getAttribute(key)就可以取到
 */
private void setAuthenticationSession(Object value){
    Subject currentUser = SecurityUtils.getSubject();
    if(null != currentUser){
        Session session = currentUser.getSession();
        System.out.println("当前Session超时时间为[" + session.getTimeout() + "]毫秒");
        session.setTimeout(1000 * 60 * 60 * 2);
        System.out.println("修改Session超时时间为[" + session.getTimeout() + "]毫秒");
        session.setAttribute("currentUser", value);
    }
}
 
Example 4
Source File: SSOComponentImpl.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@Override
public ResultMap syncSessionMaxInactiveInternal(String clientSessionId, Integer maxInactiveInternal) {
    try {
        final String sessionSerail = super.getSession(clientSessionId);
        final Session session = SerializableUtils.decode(sessionSerail);
        session.setTimeout(maxInactiveInternal * 1000);
        accessSession(session);
        return HttpStatus.OK.to();
    } catch (final Throwable e) {
        LOGGER.error("Sync session error: {}", e.getMessage());
        return ResultMap.create(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 
Example 5
Source File: ShiroRedisSessionDao.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
/**
 * save session
 * @param session
 * @throws UnknownSessionException
 */
private void saveSession(Session session) throws UnknownSessionException{
    if(session == null || session.getId() == null){
        logger.error("session or session id is null");
        return;
    }

    byte[] key = getByteKey(session.getId());
    byte[] value = SerializationUtils.serialize((Serializable) session);
    session.setTimeout(sessionTimeout);
    this.redisManager.set(key, value, sessionTimeout);
}
 
Example 6
Source File: UserOnlineServiceImpl.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void kickoutBySessionId(String sessionId) {
	Session session = getSessionBysessionId(sessionId);
	if (null != session) {
		session.setAttribute("kickout", true); // 标记为已下线
		session.setTimeout(0L); //设置session立即失效,即将其踢出系统break;
		// session.stop(); //销毁Shiro的会话
	}
}
 
Example 7
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 8
Source File: SessionInterceptor.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example 9
Source File: UserOnlineServiceImpl.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 强退用户
 * 
 * @param sessionId 会话ID
 */
@Override
public void forceLogout(String sessionId)
{
    Session session = onlineSessionDAO.readSession(sessionId);
    if (session == null)
    {
        return;
    }
    session.setTimeout(1000);
    userOnlineDao.deleteOnlineById(sessionId);
}
 
Example 10
Source File: UserOnlineService.java    From Shiro-Action with MIT License 5 votes vote down vote up
public void forceLogout(String sessionId) {
    Session session = sessionDAO.readSession(sessionId);
    if (session != null) {
        session.setTimeout(0);
        session.stop();
        sessionDAO.delete(session);
    }
}
 
Example 11
Source File: AdminRealm.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 将一些数据放到ShiroSession中,以便于其它地方使用
 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
 *
 * @param key
 * @param value
 */
private void setSession(Object key, Object value) {
    Subject currentUser = SecurityUtils.getSubject();
    if (null != currentUser) {
        Session session = currentUser.getSession();
        session.setTimeout(1800000L);
        log.info("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
        if (null != session) {
            session.setAttribute(key, value);
        }
    }
}
 
Example 12
Source File: SessionInterceptor.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example 13
Source File: AdminRealm.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 将一些数据放到ShiroSession中,以便于其它地方使用
 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
 *
 * @param key
 * @param value
 */
private void setSession(Object key, Object value) {
    Subject currentUser = SecurityUtils.getSubject();
    if (null != currentUser) {
        Session session = currentUser.getSession();
        session.setTimeout(1800000L);
        log.info("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
        if (null != session) {
            session.setAttribute(key, value);
        }
    }
}
 
Example 14
Source File: SessionServiceImpl.java    From yyblog with MIT License 4 votes vote down vote up
@Override
public boolean removeUser(String sessionId) {
    Session session = sessionDAO.readSession(sessionId);
    session.setTimeout(0);
    return true;
}
 
Example 15
Source File: SessionServiceImpl.java    From SpringAll with MIT License 4 votes vote down vote up
@Override
public boolean forceLogout(String sessionId) {
	Session session = sessionDAO.readSession(sessionId);
	session.setTimeout(0);
	return true;
}
 
Example 16
Source File: AbstractIamSessionManager.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Override
protected Session newSessionInstance(SessionContext context) {
	Session session = super.newSessionInstance(context);
	session.setTimeout(getGlobalSessionTimeout());
	return session;
}
 
Example 17
Source File: SessionManager.java    From easyweb with Apache License 2.0 4 votes vote down vote up
@Override
protected Session newSessionInstance(SessionContext context) {
	Session session = super.newSessionInstance(context);
	session.setTimeout(getGlobalSessionTimeout());
	return session;
}
 
Example 18
Source File: SessionManager.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
@Override
protected Session newSessionInstance(SessionContext context) {
	Session session = super.newSessionInstance(context);
	session.setTimeout(getGlobalSessionTimeout());
	return session;
}