org.apache.shiro.session.UnknownSessionException Java Examples

The following examples show how to use org.apache.shiro.session.UnknownSessionException. 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: IamErrorConfiguring.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public Integer getStatus(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model, Exception ex) {
	// IAM Unauthenticated?
	if ((ex instanceof UnauthenticatedException)
			|| (ex instanceof com.wl4g.devops.common.exception.iam.UnauthenticatedException)) {
		return UNAUTHC.getErrcode();
	}
	// IAM Unauthorized?
	else if ((ex instanceof UnauthorizedException)
			|| (ex instanceof com.wl4g.devops.common.exception.iam.UnauthorizedException)) {
		return UNAUTHZ.getErrcode();
	}
	// see: IamSecurityHolder
	else if (ex instanceof UnknownSessionException) {
		return PARAM_ERR.getErrcode();
	}

	// Using next chain configuring.
	return null;
}
 
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: RelationAttributesIamSessionDAO.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public void update(final Session session) throws UnknownSessionException {
	if (isNull(session) || isNull(session.getId()))
		return;
	log.debug("Updating {}", session.getId());

	// Gets logged ID.
	// PrincipalCollection pc = (PrincipalCollection)
	// session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
	// String principalId = pc != null ?
	// pc.getPrimaryPrincipal().toString() : "";

	awareRelationCache(session);

	// Update session latest expiration time to timeout.
	doPutIamSession(session);

	// Update session relation attributes timeout.
	getRelationAttrsCache(session.getId()).expireMap(safeLongToInt(MILLISECONDS.toSeconds(session.getTimeout())));
}
 
Example #4
Source File: TestBindClientContextHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testBindUnknownSession() throws Exception {
   EasyMock
      .expect(sessionDao.readSession("test"))
      .andThrow(new UnknownSessionException());
   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);
   assertFalse(client.isAuthenticated());
   assertEquals(null, client.getSessionId());

   verify();
}
 
Example #5
Source File: RedisSessionDAO.java    From shiro-redis with MIT License 5 votes vote down vote up
@Override
protected Serializable doCreate(Session session) {
	if (session == null) {
		logger.error("session is null");
		throw new UnknownSessionException("session is null");
	}
	Serializable sessionId = this.generateSessionId(session);  
       this.assignSessionId(session, sessionId);
       this.saveSession(session);
	return sessionId;
}
 
Example #6
Source File: RedisSessionDAO.java    From shiro-redis with MIT License 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");
		throw new UnknownSessionException("session or session id is null");
	}
	byte[] key;
	byte[] value;
	try {
		key = keySerializer.serialize(getRedisSessionKey(session.getId()));
		value = valueSerializer.serialize(session);
	} catch (SerializationException e) {
		logger.error("serialize session error. session id=" + session.getId());
		throw new UnknownSessionException(e);
	}
	if (expire == DEFAULT_EXPIRE) {
		this.redisManager.set(key, value, (int) (session.getTimeout() / MILLISECONDS_IN_A_SECOND));
		return;
	}
	if (expire != NO_EXPIRE && expire * MILLISECONDS_IN_A_SECOND < session.getTimeout()) {
		logger.warn("Redis session expire time: "
				+ (expire * MILLISECONDS_IN_A_SECOND)
				+ " is less than Session timeout: "
				+ session.getTimeout()
				+ " . It may cause some problems.");
	}
	this.redisManager.set(key, value, expire);
}
 
Example #7
Source File: RedisSessionDAO.java    From shiro-redis with MIT License 5 votes vote down vote up
@Override
public void update(Session session) throws UnknownSessionException {
	this.saveSession(session);
	if (this.sessionInMemoryEnabled) {
		this.setSessionToThreadLocal(session.getId(), session);
	}
}
 
Example #8
Source File: SSOServiceImpl.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void update(Session session) throws UnknownSessionException {
    final SessionDAO sessionDAO = getSessionDAO();
    if(sessionDAO != null) {
        sessionDAO.update(session);
    }
}
 
Example #9
Source File: RedisSessionDAOTest.java    From shiro-redis with MIT License 5 votes vote down vote up
@Test
public void testDoCreateNull() {
    try {
        redisSessionDAO.doCreate(null);
        fail();
    } catch (UnknownSessionException e) {
        assertEquals(e.getMessage(), "session is null");
    }
}
 
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: SSOServiceImpl.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
    final SessionDAO sessionDAO = getSessionDAO();
    if(sessionDAO != null) {
        sessionDAO.readSession(sessionId);
    }
    
    return null;
}
 
Example #12
Source File: RedisSessionDAOTest.java    From shiro-redis with MIT License 5 votes vote down vote up
@Test
public void testUpdateNull() {
    try {
        redisSessionDAO.update(null);
        fail();
    } catch (UnknownSessionException e) {
        assertEquals(e.getMessage(), "session or session id is null");
    }
}
 
Example #13
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 #14
Source File: TelegramLongPollingSessionBot.java    From TelegramBots with MIT License 5 votes vote down vote up
public Optional<Session> getSession(Message message){
    try {
        return Optional.of(sessionManager.getSession(chatIdConverter));
    } catch (UnknownSessionException e) {
        SessionContext botSession = new DefaultChatSessionContext(message.getChatId(), message.getFrom().getUserName());
        return Optional.of(sessionManager.start(botSession));
    }
}
 
Example #15
Source File: JedisSessionDAO.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
@Override
  public Session readSession(Serializable sessionId) throws UnknownSessionException {
  	try{
      	return super.readSession(sessionId);
  	}catch (UnknownSessionException e) {
	return null;
}
  }
 
Example #16
Source File: SessionManager.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
protected Session retrieveSession(SessionKey sessionKey) {
	try{
		return super.retrieveSession(sessionKey);
	}catch (UnknownSessionException e) {
   		// 获取不到SESSION不抛出异常
		return null;
	}
}
 
Example #17
Source File: JedisSessionDAO.java    From easyweb with Apache License 2.0 5 votes vote down vote up
@Override
  public Session readSession(Serializable sessionId) throws UnknownSessionException {
  	try{
      	return super.readSession(sessionId);
  	}catch (UnknownSessionException e) {
	return null;
}
  }
 
Example #18
Source File: SessionManager.java    From easyweb with Apache License 2.0 5 votes vote down vote up
protected Session retrieveSession(SessionKey sessionKey) {
	try{
		return super.retrieveSession(sessionKey);
	}catch (UnknownSessionException e) {
   		// 获取不到SESSION不抛出异常
		return null;
	}
}
 
Example #19
Source File: RedisSessionDAOTest.java    From shiro-redis with MIT License 5 votes vote down vote up
@Test
public void testUpdateEmptySession() {
    try {
        redisSessionDAO.update(emptySession);
        fail();
    } catch (UnknownSessionException e) {
        assertEquals(e.getMessage(), "session or session id is null");
    }
}
 
Example #20
Source File: JedisSessionDAO.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
    try{
        return super.readSession(sessionId);
    }catch (UnknownSessionException e) {
        return null;
    }
}
 
Example #21
Source File: LimitedMemorySessionDAO.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public Session readSession(Serializable sessionId) {
    if (sessionId == null) {
        throw new UnknownSessionException("sessionId is null");
    }

    final Session session = cache.getIfPresent(sessionId);
    if (session != null) {
        return session;
    }
    throw new UnknownSessionException(sessionId.toString());
}
 
Example #22
Source File: ShiroUtils.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 强制退出
 * 
 * @param sessionId
 *            退出的sessionId
 */
public static boolean forceLogout(String sessionId) {
	try {
		Session session = shiroConfig().getSessionManager().getSession(new DefaultSessionKey(sessionId));
		if (session != null) {
			session.setAttribute(ShiroProperties.ATTRIBUTE_SESSION_FORCE_LOGOUT, Boolean.TRUE);
		}
		return Boolean.TRUE;
	} catch (UnknownSessionException e) {
		LOGGER.warn(e.getMessage(), e);
	}
	return Boolean.FALSE;
}
 
Example #23
Source File: IPTrackingUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static MdcContextReference captureAndInitializeContext(ChannelHandlerContext ctx) {
   MdcContextReference context = MdcContext.captureMdcContext();

     try {
        Session session = getSocketSession(ctx.channel());
        if (session != null) {
         String plc = session.getActivePlace();
         if (plc != null) {
            MDC.put(MdcContext.MDC_PLACE, plc);
         }

           Client cln = session.getClient();
           if (cln != null) {
              try {
                 String prin = cln.getPrincipalName();
                 if (prin != null) {
                  MDC.put(MdcContext.MDC_BY, prin);
                 }
              } catch (UnknownSessionException ex) {
                 // ignore
              }
           }
        }
     } catch (Throwable th) {
        log.trace("could not capture session information:", th);
     }

     String chIp = ctx.attr(ip).get();
   if (chIp != null) {
      MDC.put(MdcContext.MDC_IP, chIp);
   }

   return context;
}
 
Example #24
Source File: ShiroClient.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExpired() {
	try {
		return Client.super.isExpired();
	}
	catch(UnknownSessionException e) {
		return true;
	}
}
 
Example #25
Source File: RedisSessionDao.java    From ssm with Apache License 2.0 5 votes vote down vote up
@Override
public void update(Session session) throws UnknownSessionException {
	if (LOGGER.isDebugEnabled()) {
		LOGGER.debug("shiro redis session update. sessionId={"+session.getId()+"}");
	}
	valueOperations.set(generateKey(session.getId()), session, session.getTimeout(), TimeUnit.MILLISECONDS);
}
 
Example #26
Source File: AbstractIamSessionManager.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
protected Session retrieveSession(SessionKey sessionKey) {
	try {
		return super.retrieveSession(sessionKey);
	} catch (UnknownSessionException e) {
		// Failure to obtain SESSION does not throw an exception
		return null;
	}
}
 
Example #27
Source File: JedisIamSessionDAO.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
	log.debug("readSession {}", sessionId);
	try {
		return super.readSession(sessionId);
	} catch (UnknownSessionException e) {
		return null;
	}
}
 
Example #28
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext actionContext=actionInvocation.getInvocationContext();  
	Map<String, Object> session=actionContext.getSession();  
	this.accountObj = (AccountObj)session.get(Constants.SESS_ACCOUNT);
	boolean getUserCurrentCookieFail = false; // 有 sysCurrentId 的 cookie, 但用這個cookie資料count tb_sys_usess 又與 core-web 的資料不符
	/*
	 * String contextPath = ServletActionContext.getServletContext().getContextPath();
	 * if (!contextPath.endsWith( ApplicationSiteUtils.getContextPathFromMap(Constants.getMainSystem()) ) ) {
	 */
	if ( !Constants.getSystem().equals(Constants.getMainSystem()) ) {
		/**
		 * 1. 先用admin登入
		 * 2. 登出admin 改用 tester登入
		 * 這樣的話 gsbsc-web 的 http-session 還是admin , 所以非core-web 要檢查當前CURRENT cookie 中的帳戶是否與 gsbsc-web 一樣
		 * 要是不同的話就讓這個 http-session 失效掉
		 */
		this.invalidCurrentSessionForDifferentAccount(actionContext);								
		if (accountObj==null) {
			getUserCurrentCookie(actionContext);
			if (accountObj==null && UserCurrentCookie.foundCurrent( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) ) ) {
				 // 有 sysCurrentId 的 cookie, 但用這個cookie資料count tb_sys_usess 又與 core-web 的資料不符
				getUserCurrentCookieFail = true;
			}				
		}			
	}
	if (accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) ) {
		Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
		String currentId = StringUtils.defaultString( dataMap.get("currentId") );
		if ( StringUtils.isBlank(currentId) ) {
			currentId = "NULL";
		}
		if (uSessLogHelper.countByCurrent(accountObj.getAccount(), currentId)<1) {
			return this.redirectLogin(session, getUserCurrentCookieFail);
		}						
		boolean isUnknownSession = false;
		SecurityUtils.setSecurityManager( (DefaultSecurityManager)AppContext.getBean("securityManager") );
		Subject subject = SecurityUtils.getSubject();
		try {
			if (subject.isAuthenticated() && !accountObj.getAccount().equals(subject.getPrincipal()) ) {
				subject.logout();
			}				
		} catch (ExpiredSessionException ese) {
			logger.warn( ese.getMessage().toString() );
			return this.redirectLogin(session, getUserCurrentCookieFail);
		} catch (UnknownSessionException ue) {
			logger.warn( ue.getMessage().toString() );
			isUnknownSession = true;
		}
		
		/**
		 * core-web 有 session了, 但gsbsc-web 沒有session, 所以產生gsbsc-web 的 http session
		 * 或是 apache shiro session 失效 expires
		 */			
		if ( !subject.isAuthenticated() || isUnknownSession ) {
			GreenStepBaseUsernamePasswordToken token = new GreenStepBaseUsernamePasswordToken();
			//token.setRememberMe(true);
			token.setRememberMe(false);
			token.setCaptcha("");
			token.setUsername(accountObj.getAccount());		
			token.setPassword( ((AccountVO)accountObj).getPassword().toCharArray() );
			try {					
				subject.login(token);
			} catch (UnknownAccountException uae) {
				logger.warn( uae.getMessage().toString() );
			    subject = new Subject.Builder().buildSubject();	
			    subject.login(token);
			} catch (UnknownSessionException use) {
				logger.warn( use.getMessage().toString() );
			    subject = new Subject.Builder().buildSubject();					
				/*
				Serializable sessionId = subject.getSession().getId();
				System.out.println("SESSION_ID=" + sessionId);
				subject = new Subject.Builder( (DefaultSecurityManager)AppContext.getBean("securityManager") )
					.sessionId(sessionId)
					.buildSubject();
				*/
			    subject.login(token);		
			} 
			UserAccountHttpSessionSupport.create(actionContext, accountObj);
		}
		return actionInvocation.invoke();
	}	
	return this.redirectLogin(session, getUserCurrentCookieFail);
}
 
Example #29
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);
        }
    }
 
Example #30
Source File: CassandraSessionDAO.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void update(Session session) throws UnknownSessionException {
   SimpleSession ss = assertSimpleSession(session);
   save(ss);
}