예제 #1
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
 private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
   boolean sessionInValid =
       (httpServletRequest.getRequestedSessionId() != null)
           && !httpServletRequest.isRequestedSessionIdValid();
   // System.out.println(httpServletRequest.isRequestedSessionIdValid());
   return sessionInValid;
 }
예제 #3
0
  public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    // Increment the hit count for this page. The value is saved
    // in this client's session under the name "snoop.count".
    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null) {
      count = 1;
    } else count = count + 1;
    session.setAttribute("snoop.count", count);

    out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag());
    out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    // Display the hit count for this page
    out.println(
        "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println(
        "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
  }
예제 #4
0
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    setUpApplicationContext(getServletConfig().getServletContext(), (HttpServletRequest) request);
    JspController cont = null;
    boolean sessionKeepAlive = true;
    try {
      long time = System.currentTimeMillis();
      request.setAttribute(SALMON_SERVLET_KEY, this);
      sessionKeepAlive = request.getParameter("sessionKeepAlive") != null;

      if (!_replaceFactoryInit) {
        Props p = Props.getSystemProps();
        _replaceFactoryInit = true;
        _replaceFactory = p.getBooleanProperty(Props.SYS_REPLACE_JSP_FACTORY, true);
        _cacheControllers = p.getBooleanProperty(Props.SYS_CACHE_CONTROLLERS, false);
        MessageLog.writeInfoMessage(
            "***JspServlet initialized with properties: "
                + Props.SYS_REPLACE_JSP_FACTORY
                + "="
                + _replaceFactory
                + ", "
                + Props.SYS_CACHE_CONTROLLERS
                + "="
                + _cacheControllers
                + ". To reset, change the System.properties file and restart the server.***",
            this);
      }

      //			if (_replaceFactory) {
      //				JspFactory fact = JspFactory.getDefaultFactory();
      //				if (fact == null ||
      // !fact.getClass().getName().equals("com.salmonllc.jsp.engine.JspFactoryImpl"))
      //					JspFactory.setDefaultFactory(new com.salmonllc.jsp.engine.JspFactoryImpl(fact));
      //			}

      HttpServletRequest req = (HttpServletRequest) request;
      HttpServletResponse res = (HttpServletResponse) response;

      if (sessionKeepAlive)
        com.salmonllc.util.MessageLog.writeInfoMessage(
            "JspServlet.service() keepAlive - URI=" + req.getRequestURI(),
            Props.LOG_LEVEL_10,
            this);
      else {
        notifyListeners((HttpServletRequest) request, (HttpServletResponse) response, true);
        com.salmonllc.util.MessageLog.writeInfoMessage(
            "JspServlet.service() start - URI=" + req.getRequestURI(), Props.LOG_LEVEL_10, this);
      }

      String sessID = req.getParameter(PageTag.getSessionIdentifier());
      HttpSession sess = PageTag.getSession(sessID);
      boolean sessValid = true;
      if (sess == null) {
        sessID = req.getRequestedSessionId();
        sessValid = req.isRequestedSessionIdValid();
        if (!sessValid && sessionKeepAlive) return;
        sess = req.getSession(true);
      }

      boolean onSession = false;
      boolean sessExp = false;
      if (sessID != null && !sessValid) sess.setAttribute("AppServer_SessExp", new Boolean(true));

      boolean createPage = (req.getHeader(SALMON_CREATE_PAGE_HEADER) != null);
      if (_replaceFactory) {
        Object sessToken = sess.getAttribute("AppServer_SessionToken");
        if (sessToken == null) {
          sess.setAttribute("AppServer_SessionToken", new String("tok"));
          sessToken = sess.getAttribute("AppServer_SessionToken");
        }
        synchronized (sessToken) {
          String sessName = "$jsp$" + com.salmonllc.jsp.tags.PageTag.generateSessionName(req);
          loadCachedController(sessName, sess);
          onSession = sess.getAttribute(sessName) != null;

          if (!onSession) _jspService(req, new HttpServletResponseDummy(res, null));

          cont = (JspController) sess.getAttribute(sessName);
          generateExpireResponseHeaders(res, cont.getAddExpireHeaders());

          cacheController(sessName, cont);
          cont.setSessionExpired(sessExp);
          cont.setDoPostRedirected(false);
          _jspService(req, res);
        }
      } else {
        String sessName = "$jsp$" + com.salmonllc.jsp.tags.PageTag.generateSessionName(req);
        String token = sessName + "$pageToken$";
        try {
          if (!createPage) {

            if (sess.getAttribute(token) != null) {

              /*
               * srufle : Jun 25, 2004 4 : 26 : 38 PM
               * This was put in to solve a thread deadlocking issue is was encountering
               *
               * Possible enhancements include
               * - making vars get their values from system parameters
               */
              int index = 0;
              int indexLimit = 1024;
              int sleepCount = 0;
              int sleepCountLimit = 4096;
              int sleepTime = 10;
              while (sess.getAttribute(token) != null) {
                index++;
                Thread.yield();

                if (index >= (indexLimit)) {
                  Thread.sleep(sleepTime);
                  index = 0;
                  sleepCount++;
                  if (sleepCount >= sleepCountLimit) {
                    throw (new ServletException("Thread Locked:Throwing to unlock"));
                  }
                }
              }
            }
            sess.setAttribute(token, token);
          }

          loadCachedController(sessName, sess);
          onSession = sess.getAttribute(sessName) != null;
          if (!onSession && !createPage) {
            createPage(req, res, sess, getPageURL(req, res), sess.getId());
            cont = (JspController) sess.getAttribute(sessName);

            cacheController(sessName, cont);
          } else cont = (JspController) sess.getAttribute(sessName);

          if (cont != null) {
            generateExpireResponseHeaders(res, cont.getAddExpireHeaders());
            cont.setSessionExpired(sessExp);
            cont.setDoPostRedirected(false);
            synchronized (cont) {
              _jspService(req, res);
            }
          } else {
            String contextToken = req.getHeader(SALMON_CONTEXT_TOKEN);
            _jspService(req, res);
            if (contextToken != null) {
              TagContext t = (TagContext) req.getAttribute(TagContext.TAG_CONTEXT_REQ_KEY);
              if (t != null) sess.setAttribute(contextToken, t);
            }
          }
        } catch (Exception e) {
          if (cont == null || cont.getPortletException() == null) {

            if (e instanceof SocketException) {
              // ignore java.net.SocketException
              MessageLog.writeInfoMessage("SocketException would have been thrown", this);
            } else {
              MessageLog.writeErrorMessage("service", e, this);
              throw (new ServletException(e.getMessage()));
            }
          }

        } finally {
          if (!createPage) sess.removeAttribute(token);
        }
      }

      if (!sessionKeepAlive) {
        time = (System.currentTimeMillis() - time);

        if (!createPage) addPageHit(time);

        if (Props.getSystemProps().getBooleanProperty(Props.SYS_RECORD_PAGE_TIMERS))
          recordTimerActivity(req.getRequestURI(), time, this, false);
        com.salmonllc.util.MessageLog.writeInfoMessage(
            "JspServlet.service() end - URI="
                + req.getRequestURI()
                + " Time="
                + time
                + " Init="
                + (!onSession),
            Props.LOG_LEVEL_10,
            this);
      }
    } catch (java.net.SocketException e) {
      // ignore java.net.SocketException
      MessageLog.writeInfoMessage("SocketException would have been thrown", this);
    } catch (ServletException e) {
      if (cont == null || cont.getPortletException() == null) {
        com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this);
        throw (e);
      }
    } catch (IOException e) {
      com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this);
      throw (e);
    } catch (Exception e) {
      com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this);
      throw (new ServletException(e));
    } finally {
      try {
        if (!sessionKeepAlive)
          notifyListeners((HttpServletRequest) request, (HttpServletResponse) response, false);
      } catch (Exception e) {
        com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this);
        throw (new ServletException(e));
      }
    }
  }
 public boolean isRequestedSessionIdValid() {
   return request.isRequestedSessionIdValid();
 }
예제 #6
0
  public TaskHttpServletRequest(HttpServletRequest wrapping, Task task) {
    this.session = wrapping.getSession();
    String location = wrapping.getParameter("url");

    cookies = wrapping.getCookies();
    characterEncoding = wrapping.getCharacterEncoding();
    authType = wrapping.getAuthType();
    headerNames = new Vector<String>();
    headers = new MultiMap();
    for (Enumeration e = wrapping.getHeaderNames(); e.hasMoreElements(); ) {
      String headerName = (String) e.nextElement();
      for (Enumeration f = wrapping.getHeaders(headerName); f.hasMoreElements(); ) {
        String headerValue = (String) f.nextElement();
        headers.add(headerName, headerValue);
      }
    }
    contextPath = wrapping.getContextPath();
    pathInfo = wrapping.getPathInfo();
    pathTranslated = wrapping.getPathTranslated();
    remoteUser = wrapping.getRemoteUser(); // TODO check if needed
    requestedSessionId = wrapping.getRequestedSessionId(); // TODO check if needed
    userPrincipal = wrapping.getUserPrincipal(); // TODO check if needed
    requestedSessionIdFromCookie = wrapping.isRequestedSessionIdFromCookie();
    requestedSessionIdFromURL = wrapping.isRequestedSessionIdFromURL();
    requestedSessionIdValid = wrapping.isRequestedSessionIdValid();
    localAddr = wrapping.getLocalAddr();
    localName = wrapping.getLocalName();
    localPort = wrapping.getLocalPort();
    locale = wrapping.getLocale();
    locales = new Vector<Locale>();
    for (Enumeration e = wrapping.getLocales();
        e.hasMoreElements();
        locales.add((Locale) e.nextElement())) ;
    protocol = wrapping.getProtocol();
    remoteAddr = wrapping.getRemoteAddr();
    remoteHost = wrapping.getRemoteHost();
    remotePort = wrapping.getRemotePort();
    scheme = wrapping.getScheme();
    serverName = wrapping.getServerName();
    serverPort = wrapping.getServerPort();
    secure = wrapping.isSecure();

    // Extract the query (everything after ?)
    int idx = location.indexOf('?');
    query = null;
    if (idx != -1) {
      query = location.substring(idx + 1);
    }

    // Extract the URI (everything before ?)
    uri = location;
    if (idx != -1) {
      uri = uri.substring(0, idx);
    }

    // Servlet path (same as URI?)
    servletPath = uri;

    // Extract parameters
    params = new Hashtable<String, String[]>();
    if (query != null) {
      StringTokenizer t = new StringTokenizer(query, "&");
      while (t.hasMoreTokens()) {
        String token = t.nextToken();
        idx = token.indexOf('=');
        String name = token;
        String val = null;
        if (idx != -1) {
          name = token.substring(0, idx);
          val = token.substring(idx + 1);
        } else {
          val = "";
        }
        String[] vals = params.get(name);
        if (vals == null) {
          vals = new String[] {val};
        } else {
          String[] nvals = new String[vals.length + 1];
          System.arraycopy(vals, 0, nvals, 0, vals.length);
          nvals[vals.length] = val;
          vals = nvals;
        }
        params.put(name, vals);
      }
    }

    // Initialise attributes
    attributes = new Hashtable<String, Object>();

    // Create the URL (the URL with protocol / host / post)
    try {
      URL u = new URL(new URL(wrapping.getRequestURL().toString()), uri);
      url = new StringBuffer(u.toExternalForm());
    } catch (MalformedURLException e) {
    }

    setAttribute(ATTR_TASK, task);
  }
  private void doPortalAuthentication(HttpServletRequest request) {
    // Clear out the existing session for the user if they have one
    String targetUid = null;
    String originalUid = null;
    String originalEventSessionId = null;
    boolean swap = false;
    String swapperProfile = null;

    final String requestedSessionId = request.getRequestedSessionId();

    if (request.isRequestedSessionIdValid()) {
      if (logger.isDebugEnabled()) {
        logger.debug("doPortalAuthentication for valid requested session id " + requestedSessionId);
      }

      try {
        HttpSession s = request.getSession(false);

        if (s != null) {
          // Check if this is a swapped user hitting the Login servlet
          originalUid = this.identitySwapperManager.getOriginalUsername(s);
        }

        // No original person in session so check for swap request
        if (originalUid == null) {
          targetUid = this.identitySwapperManager.getTargetUsername(s);
          if (targetUid != null) {
            final IPerson person = personManager.getPerson(request);
            originalUid = person.getName();
            swap = true;
            swapperProfile = identitySwapperManager.getTargetProfile(s);
          }
        }
        // Original person in session so this must be an un-swap request
        else {
          if (logger.isDebugEnabled()) {
            logger.trace(
                "This is an un-swap request swapping back from impersonated "
                    + targetUid
                    + " to original user "
                    + originalUid
                    + ".");
          }

          final IPerson person = personManager.getPerson(request);
          targetUid = person.getName();
        }

        if (s != null) {
          if (logger.isDebugEnabled()) {
            logger.debug("Invalidating the impersonated session in un-swapping.");
          }

          s.invalidate();
        }
      } catch (IllegalStateException ise) {
        // ISE indicates session was already invalidated.
        // This is fine.  This servlet trying to guarantee that the session has been invalidated;
        // it doesn't have to insist that it is the one that invalidated it.
        if (logger.isTraceEnabled()) {
          logger.trace("LoginServlet attempted to invalidate an already invalid session.", ise);
        }
      }
    } else {
      if (logger.isTraceEnabled()) {
        logger.trace(
            "Requested session id "
                + requestedSessionId
                + " was not valid "
                + "so no attempt to apply swapping rules.");
      }
    }

    //  Create the user's session
    HttpSession s = request.getSession(true);

    IPerson person = null;
    try {
      final HashMap<String, String> principals;
      final HashMap<String, String> credentials;

      // Get the person object associated with the request
      person = personManager.getPerson(request);

      // If doing an identity swap
      if (targetUid != null && originalUid != null) {
        if (swap) {
          swapperLog.warn("Swapping identity for '" + originalUid + "' to '" + targetUid + "'");

          // Track the originating user
          this.identitySwapperManager.setOriginalUser(s, originalUid, targetUid);

          // Setup the swapped person
          person.setUserName(targetUid);
        } else {
          swapperLog.warn(
              "Reverting swapped identity from '" + targetUid + "' to '" + originalUid + "'");

          person.setUserName(originalUid);
        }

        // Setup the custom security context
        final IdentitySwapperPrincipal identitySwapperPrincipal =
            new IdentitySwapperPrincipal(person);
        final IdentitySwapperSecurityContext identitySwapperSecurityContext =
            new IdentitySwapperSecurityContext(identitySwapperPrincipal);
        person.setSecurityContext(identitySwapperSecurityContext);

        principals = new HashMap<String, String>();
        credentials = new HashMap<String, String>();
      }
      // Norm authN path
      else {
        // WE grab all of the principals and credentials from the request and load
        // them into their respective HashMaps.
        principals = getPropertyFromRequest(principalTokens, request);
        credentials = getPropertyFromRequest(credentialTokens, request);
      }

      // Attempt to authenticate using the incoming request
      authenticationService.authenticate(request, principals, credentials, person);
    } catch (Exception e) {
      // Log the exception
      logger.error("Exception authenticating the request", e);
      // Reset everything
      request.getSession(false).invalidate();
      // Add the authentication failure
      request.getSession(true).setAttribute(LoginController.AUTH_ERROR_KEY, Boolean.TRUE);
    }

    final String requestedProfile = request.getParameter(LoginController.REQUESTED_PROFILE_KEY);

    if (requestedProfile != null) {

      final ProfileSelectionEvent event =
          new ProfileSelectionEvent(this, requestedProfile, person, request);
      this.eventPublisher.publishEvent(event);

    } else if (swapperProfile != null) {

      final ProfileSelectionEvent event =
          new ProfileSelectionEvent(this, swapperProfile, person, request);
      this.eventPublisher.publishEvent(event);

    } else {
      if (logger.isTraceEnabled()) {
        logger.trace("No requested or swapper profile requested so no profile selection event.");
      }
    }
  }