protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { String[] sidWebApps = ServletRequestUtils.getStringParameters(request, "sid_webapp"); for (int i = 0; i < sidWebApps.length; i++) { if (sidWebApps[i] != null) { String[] ss = sidWebApps[i].split(";"); if (ss.length == 2) { String sessionId = ss[0]; String appName = ss[1]; Context context = getContainerWrapper().getTomcatContainer().findContext(appName); if (context != null) { Manager manager = context.getManager(); Session session = manager.findSession(sessionId); if (session != null && session.isValid()) { session.expire(); } } else { return new ModelAndView("errors/paramerror"); } } else { return new ModelAndView("errors/paramerror"); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
/** * Test for issue #49: Sessions not associated with a memcached node don't get associated as soon * as a memcached is available * * @throws InterruptedException * @throws IOException * @throws TimeoutException * @throws ExecutionException */ @Test(enabled = true) public void testNotAssociatedSessionGetsAssociatedIssue49() throws InterruptedException, IOException, ExecutionException, TimeoutException { _daemon.stop(); final SessionManager manager = _tomcat1.getManager(); manager.setMaxInactiveInterval(5); manager.setSticky(true); final SessionIdFormat sessionIdFormat = new SessionIdFormat(); final Session session = manager.createSession(null); assertNull(sessionIdFormat.extractMemcachedId(session.getId())); _daemon.start(); // Wait so that the daemon will be available and the client can reconnect (async get didn't do // the trick) Thread.sleep(4000); final String newSessionId = manager.getMemcachedSessionService().changeSessionIdOnMemcachedFailover(session.getId()); assertNotNull(newSessionId); assertEquals(newSessionId, session.getId()); assertEquals(sessionIdFormat.extractMemcachedId(newSessionId), _memcachedNodeId); }
public String getCreationTime(String sessionId) { Session s = (Session) sessions.get(sessionId); if (s == null) { return ""; } return new Date(s.getCreationTime()).toString(); }
public void expireSession(String sessionId) { Session s = (Session) sessions.get(sessionId); if (s == null) { return; } s.expire(); }
/** * Returns true if the request specifies a JSESSIONID that is valid within the context of this * ApplicationHttpRequest, false otherwise. * * @return true if the request specifies a JSESSIONID that is valid within the context of this * ApplicationHttpRequest, false otherwise. */ public boolean isRequestedSessionIdValid() { if (crossContext) { String requestedSessionId = getRequestedSessionId(); if (requestedSessionId == null) return (false); if (context == null) return (false); Manager manager = context.getManager(); if (manager == null) return (false); Session session = null; try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && session.isValid()) { return (true); } else { return (false); } } else { return super.isRequestedSessionIdValid(); } }
public void expireSession(String sessionId) { Session s = (Session) sessions.get(sessionId); if (s == null) { if (log.isInfoEnabled()) log.info("Session not found " + sessionId); return; } s.expire(); }
public String getCreationTime(String sessionId) { Session s = (Session) sessions.get(sessionId); if (s == null) { if (log.isInfoEnabled()) log.info("Session not found " + sessionId); return ""; } return new Date(s.getCreationTime()).toString(); }
/** * Expire sessions whose lifetime is greater than or equal to <code>maxLifetimeMillis</code> * * @param maxLifetimeMillis The maximum session lifetime in milliseconds */ public void expireSessions(long maxLifetimeMillis) { Session[] sessions = context.getManager().findSessions(); for (Session session : sessions) { if ((System.currentTimeMillis() - session.getCreationTime()) >= maxLifetimeMillis) { session.expire(); } } }
/** * For debugging: get a session attribute * * @param sessionId * @param key * @return The attribute value, if found, null otherwise */ public String getSessionAttribute(String sessionId, String key) { Session s = (Session) sessions.get(sessionId); if (s == null) { return null; } Object o = s.getSession().getAttribute(key); if (o == null) return null; return o.toString(); }
/** * For debugging: get a session attribute * * @param sessionId * @param key * @return The attribute value, if found, null otherwise */ public String getSessionAttribute(String sessionId, String key) { Session s = (Session) sessions.get(sessionId); if (s == null) { if (log.isInfoEnabled()) log.info("Session not found " + sessionId); return null; } Object o = s.getSession().getAttribute(key); if (o == null) return null; return o.toString(); }
public Object authorize(AbstractSecurityContext context) throws Exception { startAuthorization(context); HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteManager.getCurrentInstance(); HttpServletRequest httpRequest = graniteContext.getRequest(); Request request = getRequest(httpRequest); Session session = request.getSessionInternal(); request.setAuthType(session.getAuthType()); request.setUserPrincipal(session.getPrincipal()); if (context.getDestination().isSecured()) { Principal principal = getPrincipal(httpRequest); if (principal == null) { if (httpRequest.getRequestedSessionId() != null) { HttpSession httpSession = httpRequest.getSession(false); if (httpSession == null || httpRequest.getRequestedSessionId().equals(httpSession.getId())) throw SecurityServiceException.newSessionExpiredException("Session expired"); } throw SecurityServiceException.newNotLoggedInException("User not logged in"); } Realm realm = getRealm(httpRequest); boolean accessDenied = true; for (String role : context.getDestination().getRoles()) { if (realm.hasRole(principal, role)) { accessDenied = false; break; } } if (accessDenied) throw SecurityServiceException.newAccessDeniedException("User not in required role"); } try { return endAuthorization(context); } catch (InvocationTargetException e) { for (Throwable t = e; t != null; t = t.getCause()) { // Don't create a dependency to javax.ejb in SecurityService... if (t instanceof SecurityException || "javax.ejb.EJBAccessException".equals(t.getClass().getName())) throw SecurityServiceException.newAccessDeniedException(t.getMessage()); } throw e; } }
/** * Add this Session to the set of active Sessions for this Manager. * * @param session Session to be added */ public void add(Session session) { sessions.put(session.getIdInternal(), session); int size = sessions.size(); if (size > maxActive) { maxActive = size; } }
@Override public void remove(Session session, boolean update) { Jedis jedis = null; Boolean error = true; log.trace("Removing session ID : " + session.getId()); try { jedis = acquireConnection(); jedis.del(session.getId()); error = false; } finally { if (jedis != null) { returnConnection(jedis, error); } } }
/** * Reset DeltaRequest from session * * @param session HttpSession from current request or cross context session */ protected void resetDeltaRequest(Session session) { if (log.isDebugEnabled()) { log.debug( sm.getString( "ReplicationValve.resetDeltaRequest", session.getManager().getContainer().getName())); } ((DeltaSession) session).resetDeltaRequest(); }
/** * Send all changed cross context sessions to backups * * @param containerCluster */ protected void sendCrossContextSession(CatalinaCluster containerCluster) { List<DeltaSession> sessions = crossContextSessions.get(); if (sessions != null && sessions.size() > 0) { for (Iterator<DeltaSession> iter = sessions.iterator(); iter.hasNext(); ) { Session session = iter.next(); if (log.isDebugEnabled()) log.debug( sm.getString( "ReplicationValve.crossContext.sendDelta", session.getManager().getContainer().getName())); sendMessage(session, (ClusterManager) session.getManager(), containerCluster); if (doStatistics()) { nrOfCrossContextSendRequests++; } } } }
/** * Construct and return a new session object, based on the default settings specified by this * Manager's properties. The session id specified will be used as the session id. If a new session * cannot be created for any reason, return <code>null</code>. * * @param sessionId The session id which should be used to create the new session; if <code>null * </code>, a new session id will be generated * @exception IllegalStateException if a new session cannot be instantiated for any reason */ @Override public Session createSession(String sessionId) { if ((maxActiveSessions >= 0) && (getActiveSessions() >= maxActiveSessions)) { rejectedSessions++; throw new IllegalStateException(sm.getString("managerBase.createSession.ise")); } // Recycle or create a Session instance Session session = createEmptySession(); // Initialize the properties of the new session and return it session.setNew(true); session.setValid(true); session.setCreationTime(System.currentTimeMillis()); session.setMaxInactiveInterval(this.maxInactiveInterval); String id = sessionId; if (id == null) { id = generateSessionId(); } session.setId(id); sessionCounter++; SessionTiming timing = new SessionTiming(session.getCreationTime(), 0); synchronized (sessionCreationTiming) { sessionCreationTiming.add(timing); sessionCreationTiming.poll(); } return (session); }
/** * Test for JBAS-5404 * * @throws Exception */ public void testMaxInactiveIntervalReplication() throws Exception { log.info("Enter testMaxInactiveIntervalReplication"); ++testCount; JBossCacheManager jbcm0 = SessionTestUtil.createManager("test" + testCount, 5, false, null, true, true, null, caches); JBossWebMetaData webMetaData = SessionTestUtil.createWebMetaData(2); jbcm0.init("test.war", webMetaData); jbcm0.start(); JBossCacheManager jbcm1 = SessionTestUtil.createManager("test" + testCount, 5, false, null, true, true, null, caches); jbcm1.init("test.war", webMetaData); jbcm1.start(); // Set up a session String id = "1"; Session sess = jbcm0.findSession(id); assertNull("session does not exist", sess); sess = jbcm0.createSession(id); sess.access(); sess.getSession().setAttribute("test", "test"); jbcm0.storeSession(sess); sess.endAccess(); assertEquals("Session count correct", 1, jbcm0.getActiveSessionCount()); assertEquals("Local session count correct", 1, jbcm0.getLocalActiveSessionCount()); assertEquals("Session count correct", 1, jbcm1.getActiveSessionCount()); assertEquals("Local session count correct", 0, jbcm1.getLocalActiveSessionCount()); // Confirm a session timeout clears space sess = jbcm0.findSession(id); sess.access(); sess.setMaxInactiveInterval(1); jbcm0.storeSession(sess); sess.endAccess(); SessionTestUtil.sleepThread(1005); jbcm1.backgroundProcess(); assertEquals("Session count correct", 1, jbcm0.getActiveSessionCount()); assertEquals("Local session count correct", 1, jbcm0.getLocalActiveSessionCount()); assertEquals("Session count correct", 0, jbcm1.getActiveSessionCount()); assertEquals("Local session count correct", 0, jbcm1.getLocalActiveSessionCount()); jbcm0.backgroundProcess(); assertEquals("Session count correct", 0, jbcm0.getActiveSessionCount()); assertEquals("Local session count correct", 0, jbcm0.getLocalActiveSessionCount()); assertEquals("Session count correct", 0, jbcm1.getActiveSessionCount()); assertEquals("Local session count correct", 0, jbcm1.getLocalActiveSessionCount()); }
/** * Returns information about the session with the given session id. * * <p>The session information is organized as a HashMap, mapping session attribute names to the * String representation of their values. * * @param sessionId Session id * @return HashMap mapping session attribute names to the String representation of their values, * or null if no session with the specified id exists, or if the session does not have any * attributes */ public HashMap getSession(String sessionId) { Session s = (Session) sessions.get(sessionId); if (s == null) { return null; } Enumeration ee = s.getSession().getAttributeNames(); if (ee == null || !ee.hasMoreElements()) { return null; } HashMap map = new HashMap(); while (ee.hasMoreElements()) { String attrName = (String) ee.nextElement(); map.put(attrName, getSessionAttribute(sessionId, attrName)); } return map; }
/** * Serialize a session into a byte array<br> * This method simple calls the writeObjectData method on the session and returns the byte data * from that call * * @param session - the session to be serialized * @return a byte array containing the session data, null if the serialization failed */ protected byte[] writeSession(Session session) { try { java.io.ByteArrayOutputStream session_data = new java.io.ByteArrayOutputStream(); java.io.ObjectOutputStream session_out = new java.io.ObjectOutputStream(session_data); session_out.flush(); boolean hasPrincipal = session.getPrincipal() != null; session_out.writeBoolean(hasPrincipal); if (hasPrincipal) { session_out.writeObject( SerializablePrincipal.createPrincipal((GenericPrincipal) session.getPrincipal())); } // end if ((ReplicatedSession) session).writeObjectData(session_out); return session_data.toByteArray(); } catch (Exception x) { log.error("Failed to serialize the session!", x); } return null; }
/** * Adds a <code>Session</code> to the list of those associated with this SSO. * * @param sso The <code>SingleSignOn</code> valve that is managing the SSO session. * @param session The <code>Session</code> being associated with the SSO. */ public synchronized void addSession(SingleSignOn sso, Session session) { for (int i = 0; i < sessions.length; i++) { if (session == sessions[i]) return; } Session results[] = new Session[sessions.length + 1]; System.arraycopy(sessions, 0, results, 0, sessions.length); results[sessions.length] = session; sessions = results; session.addSessionListener(sso); }
private boolean doIsEncodeable(Request hreq, Session session, String location) { // Is this a valid absolute URL? URL url = null; try { url = new URL(location); } catch (MalformedURLException e) { return (false); } // Does this URL match down to (and including) the context path? if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol())) { return (false); } if (!hreq.getServerName().equalsIgnoreCase(url.getHost())) { return (false); } int serverPort = hreq.getServerPort(); if (serverPort == -1) { if ("https".equals(hreq.getScheme())) { serverPort = 443; } else { serverPort = 80; } } int urlPort = url.getPort(); if (urlPort == -1) { if ("https".equals(url.getProtocol())) { urlPort = 443; } else { urlPort = 80; } } if (serverPort != urlPort) { return (false); } String contextPath = getContext().getPath(); if (contextPath != null) { String file = url.getFile(); if ((file == null) || !file.startsWith(contextPath)) { return (false); } String tok = ";" + SessionConfig.getSessionUriParamName(request.getContext()) + "=" + session.getIdInternal(); if (file.indexOf(tok, contextPath.length()) >= 0) { return (false); } } // This URL belongs to our web application, so it is encodeable return (true); }
public void login(Object credentials) throws SecurityServiceException { String[] decoded = decodeBase64Credentials(credentials); HttpGraniteContext context = (HttpGraniteContext) GraniteManager.getCurrentInstance(); HttpServletRequest httpRequest = context.getRequest(); Realm realm = getRealm(httpRequest); Principal principal = realm.authenticate(decoded[0], decoded[1]); if (principal == null) throw SecurityServiceException.newInvalidCredentialsException("Wrong username or password"); Request request = getRequest(httpRequest); request.setAuthType(AUTH_TYPE); request.setUserPrincipal(principal); Session session = request.getSessionInternal(); session.setAuthType(AUTH_TYPE); session.setPrincipal(principal); session.setNote(Constants.SESS_USERNAME_NOTE, decoded[0]); session.setNote(Constants.SESS_PASSWORD_NOTE, decoded[1]); }
/** * Remove this Session from the active Sessions for this Manager. * * @param session Session to be removed * @param update Should the expiration statistics be updated */ @Override public void remove(Session session, boolean update) { // If the session has expired - as opposed to just being removed from // the manager because it is being persisted - update the expired stats if (update) { long timeNow = System.currentTimeMillis(); int timeAlive = (int) (timeNow - session.getCreationTimeInternal()) / 1000; updateSessionMaxAliveTime(timeAlive); expiredSessions.incrementAndGet(); SessionTiming timing = new SessionTiming(timeNow, timeAlive); synchronized (sessionExpirationTiming) { sessionExpirationTiming.add(timing); sessionExpirationTiming.poll(); } } if (session.getIdInternal() != null) { sessions.remove(session.getIdInternal()); } }
/** * Add this Session to the set of active Sessions for this Manager. * * @param session Session to be added */ @Override public void add(Session session) { sessions.put(session.getIdInternal(), session); int size = getActiveSessions(); if (size > maxActive) { synchronized (maxActiveUpdateLock) { if (size > maxActive) { maxActive = size; } } } }
/** * Returns information about the session with the given session id. * * <p>The session information is organized as a HashMap, mapping session attribute names to the * String representation of their values. * * @param sessionId Session id * @return HashMap mapping session attribute names to the String representation of their values, * or null if no session with the specified id exists, or if the session does not have any * attributes */ public HashMap<String, String> getSession(String sessionId) { Session s = sessions.get(sessionId); if (s == null) { if (log.isInfoEnabled()) { log.info("Session not found " + sessionId); } return null; } Enumeration<String> ee = s.getSession().getAttributeNames(); if (ee == null || !ee.hasMoreElements()) { return null; } HashMap<String, String> map = new HashMap<String, String>(); while (ee.hasMoreElements()) { String attrName = ee.nextElement(); map.put(attrName, getSessionAttribute(sessionId, attrName)); } return map; }
/** * Save the specified Session into this Store. Any previously saved information for the associated * session identifier is replaced. * * @param session Session to be saved * @exception IOException if an input/output error occurs */ @Override public void save(Session session) throws IOException { // Open an output stream to the specified pathname, if any File file = file(session.getIdInternal()); if (file == null) { return; } if (manager.getContext().getLogger().isDebugEnabled()) { manager .getContext() .getLogger() .debug( sm.getString( getStoreName() + ".saving", session.getIdInternal(), file.getAbsolutePath())); } try (FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos))) { ((StandardSession) session).writeObjectData(oos); } }
@Override public ApiResponse signOutAll() { ApiResponse response = ApiResponse.createDefaultApiResponse(); HttpServletRequest request = HttpUtil.getRequest(); HttpSession httpSession = HttpUtil.getSession(); if (request instanceof RequestFacade) { Field requestField = null; try { requestField = request.getClass().getDeclaredField("request"); } catch (NoSuchFieldException e) { e.printStackTrace(); } if (requestField != null) { requestField.setAccessible(true); Request req = null; try { req = (Request) requestField.get(request); } catch (IllegalAccessException e) { e.printStackTrace(); } if (req != null) { Context context = req.getContext(); Manager manager = context.getManager(); Session[] sessions = manager.findSessions(); if (sessions != null) { for (Session session : sessions) { if (!httpSession.getId().equals(session.getId())) { session.expire(); } } } } } } return response; }
/** * Reinstantiates a serialized session from the data passed in. This will first call * createSession() so that we get a fresh instance with all the managers set and all the transient * fields validated. Then it calls Session.readObjectData(byte[]) to deserialize the object * * @param data - a byte array containing session data * @return a valid Session object, null if an error occurs */ protected Session readSession(byte[] data, String sessionId) { try { ReplicationStream session_in = getReplicationStream(data); Session session = sessionId != null ? this.findSession(sessionId) : null; boolean isNew = (session == null); // clear the old values from the existing session if (session != null) { ReplicatedSession rs = (ReplicatedSession) session; rs.expire(false); // cleans up the previous values, since we are not doing removes session = null; } // end if if (session == null) { session = createSession(null, false, false); sessions.remove(session.getIdInternal()); } boolean hasPrincipal = session_in.readBoolean(); SerializablePrincipal p = null; if (hasPrincipal) p = (SerializablePrincipal) session_in.readObject(); ((ReplicatedSession) session).readObjectData(session_in); if (hasPrincipal) session.setPrincipal(p.getPrincipal(getContainer().getRealm())); ((ReplicatedSession) session).setId(sessionId, isNew); ReplicatedSession rsession = (ReplicatedSession) session; rsession.setAccessCount(1); session.setManager(this); session.setValid(true); rsession.setLastAccessedTime(System.currentTimeMillis()); rsession.setThisAccessedTime(System.currentTimeMillis()); ((ReplicatedSession) session).setAccessCount(0); session.setNew(false); if (log.isTraceEnabled()) log.trace( "Session loaded id=" + sessionId + " actualId=" + session.getId() + " exists=" + this.sessions.containsKey(sessionId) + " valid=" + rsession.isValid()); return session; } catch (Exception x) { log.error("Failed to deserialize the session!", x); } return null; }
public void logout() throws SecurityServiceException { HttpGraniteContext context = (HttpGraniteContext) GraniteManager.getCurrentInstance(); Session session = getSession(context.getRequest(), false); if (session != null && session.getPrincipal() != null) { session.setAuthType(null); session.setPrincipal(null); session.removeNote(Constants.SESS_USERNAME_NOTE); session.removeNote(Constants.SESS_PASSWORD_NOTE); session.expire(); } }
/** * Register an authenticated Principal and authentication type in our request, in the current * session (if there is one), and with our SingleSignOn valve, if there is one. Set the * appropriate cookie to be returned. * * @param request The servlet request we are processing * @param response The servlet response we are generating * @param principal The authenticated Principal to be registered * @param authType The authentication type to be registered * @param username Username used to authenticate (if any) * @param password Password used to authenticate (if any) */ protected void register( HttpRequest request, HttpResponse response, Principal principal, String authType, String username, String password) { if (debug >= 1) log("Authenticated '" + principal.getName() + "' with type '" + authType + "'"); // Cache the authentication information in our request request.setAuthType(authType); request.setUserPrincipal(principal); // Cache the authentication information in our session, if any if (cache) { Session session = getSession(request, false); if (session != null) { session.setAuthType(authType); session.setPrincipal(principal); if (username != null) session.setNote(Constants.SESS_USERNAME_NOTE, username); else session.removeNote(Constants.SESS_USERNAME_NOTE); if (password != null) session.setNote(Constants.SESS_PASSWORD_NOTE, password); else session.removeNote(Constants.SESS_PASSWORD_NOTE); } } // Construct a cookie to be returned to the client if (sso == null) return; HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); HttpServletResponse hres = (HttpServletResponse) response.getResponse(); String value = generateSessionId(); Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, value); cookie.setMaxAge(-1); cookie.setPath("/"); hres.addCookie(cookie); // Register this principal with our SSO valve sso.register(value, principal, authType, username, password); request.setNote(Constants.REQ_SSOID_NOTE, value); }