Example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdFromCookie

List of usage examples for javax.servlet.http HttpServletRequest isRequestedSessionIdFromCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdFromCookie.

Prototype

public boolean isRequestedSessionIdFromCookie();

Source Link

Document

<p>Checks whether the requested session ID was conveyed to the server as an HTTP cookie.</p>

Usage

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data./*from  ww  w .j av  a  2s . co m*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.directwebremoting.dwrp.PollHandler.java

/**
 * Check that this request is not subject to a CSRF attack
 * @param request The original browser's request
 * @param bodySessionId The session id //ww w.  j  a v a 2s. c  om
 */
private void checkNotCsrfAttack(HttpServletRequest request, String bodySessionId) {
    // A check to see that this isn't a csrf attack
    // http://en.wikipedia.org/wiki/Cross-site_request_forgery
    // http://www.tux.org/~peterw/csrf.txt
    if (request.isRequestedSessionIdValid() && request.isRequestedSessionIdFromCookie()) {
        String headerSessionId = request.getRequestedSessionId();
        if (headerSessionId.length() > 0) {
            // Normal case; if same session cookie is supplied by DWR and
            // in HTTP header then all is ok
            if (headerSessionId.equals(bodySessionId)) {
                return;
            }

            // Weblogic adds creation time to the end of the incoming
            // session cookie string (even for request.getRequestedSessionId()).
            // Use the raw cookie instead
            Cookie[] cookies = request.getCookies();
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(sessionCookieName) && cookie.getValue().equals(bodySessionId)) {
                    return;
                }
            }

            // Otherwise error
            log.error("A request has been denied as a potential CSRF attack.");
            throw new SecurityException("Session Error");
        }
    }
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXMakeRequestHandler.java

@Override
protected HttpRequest buildHttpRequest(HttpServletRequest request) throws GadgetException {
    HttpRequest req = super.buildHttpRequest(request);

    if (!svc.propagateJSESSIONIDToTrustedHosts()) {
        return req;
    }//from   w w w.j  a va  2s  . co m

    String auth = req.getUri().getAuthority();
    boolean done = false;
    if (auth != null) {
        if (auth.indexOf(':') != -1) {
            auth = auth.substring(0, auth.indexOf(':')); // foo:8080
        }
        for (String host : svc.getTrustedHosts()) {
            if (host.trim().equalsIgnoreCase(auth.trim())) {
                if (request.isRequestedSessionIdValid()) {
                    if (request.isRequestedSessionIdFromCookie()) {
                        req.addHeader(COOKIE, JSESSIONCOOKIE + request.getRequestedSessionId());
                        done = true;
                    }
                }
                break;
            }
        }
        if (!done) {
            String path = req.getUri().getPath();
            if ((path.startsWith(NUXEO_REST)) || (path.startsWith(NUXEO_WEBENG))) {
                req.addHeader(COOKIE, JSESSIONCOOKIE + request.getRequestedSessionId());
            }
        }
    }
    return req;
}

From source file:org.wings.session.PortletWingServlet.java

public final PortletSessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response,
        boolean createSessionServlet) throws ServletException {

    // WingS-Portlet-Bridge: for the bridge we are using the portletSession to
    // seperate between the instances of one portlet through the portlet scope
    RenderRequest renderRequest = (RenderRequest) request.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST);
    if (renderRequest == null) {
        log.error("WingS-Portlet-Bridge: cant get RenderRequest because " + "the request attribute "
                + Const.REQUEST_ATTR_RENDER_REQUEST + " is null!");
    }/*from w  w  w  . j av a2  s .  c  om*/
    final PortletSession portletSession = renderRequest.getPortletSession();

    // WingS-Portlet-Bridge: get the wings mainclass for current mode
    String lookupName = "SessionServlet";
    lookupName = "SessionServlet:" + (String) renderRequest.getAttribute(Const.REQUEST_ATTR_WINGS_CLASS);

    log.info("WingS-Portlet-Bridge: loaded mainclass " + lookupName
            + " for PortletSessionServlet identificaction");

    // it should be enough to synchronize on the http session object...
    synchronized (portletSession) {
        PortletSessionServlet sessionServlet = null;

        if (portletSession != null) {
            // WingS-Portlet-Bridge: changed for portlet scope
            sessionServlet = (PortletSessionServlet) portletSession.getAttribute(lookupName,
                    PortletSession.PORTLET_SCOPE);
        }

        // Sanity check - maybe this is a stored/deserialized session servlet?
        if (sessionServlet != null && !sessionServlet.isValid()) {
            sessionServlet.destroy();
            sessionServlet = null;
            log.debug("session servlet exists but is not valid");
        }

        /*
         * we are only interested in a new session, if the response is
         * not null. If it is null, then we just called getSessionServlet()
         * for lookup purposes and are satisfied, if we don't get anything.
         */
        if (sessionServlet == null) {
            if (createSessionServlet) {
                log.info("no session servlet, create new one");
                sessionServlet = newSession(request, response);
                portletSession.setAttribute(lookupName, sessionServlet, PortletSession.PORTLET_SCOPE);
            } else {
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder().append("session id: ")
                    .append(request.getRequestedSessionId()).append(", created at: ")
                    .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                            .format(new java.util.Date(portletSession.getCreationTime())))
                    .append(", identified via:")
                    .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "")
                    .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ")
                    .append(portletSession.getMaxInactiveInterval()).append("s ");
            log.debug(message.toString());
            //log.debug("session valid " + request.isRequestedSessionIdValid());
            //log.debug("session httpsession id " + httpSession.getId());
            //log.debug("session httpsession new " + httpSession.isNew());
            //log.debug("session last accessed at " +
            //        new java.util.Date(httpSession.getLastAccessedTime()));
            //log.debug("session expiration timeout (s) " +
            //        httpSession.getMaxInactiveInterval());
            //log.debug("session contains wings session " +
            //        (httpSession.getAttribute(lookupName) != null));
        }

        sessionServlet.getSession().getExternalizeManager().setResponse(response);

        /* Handling of the requests character encoding.
         * --------------------------------------------
         * The following block is needed for a correct handling of
         * non-ISO-8859-1 data:
         *
         * Using LocaleCharacterSet and/or charset.properties we can
         * advise the client to use i.e. UTF-8 as character encoding.
         * Once told the browser consequently also encodes his requests
         * in the choosen characterset of the sings session. This is
         * achieved by adding the HTML code
         * <meta http-equiv="Content-Type" content="text/html;charset="<charset>">
         * to the generated pages.
         *
         * If the user hasn't overridden the encoding in their browser,
         * then all form data (e.g. mueller) is submitted with data encoded
         * like m%C3%BCller because byte pair C3 BC is how the german
         * u-umlaut is represented in UTF-8. If the form is
         * iso-8859-1 encoded then you get m%FCller, because byte FC is
         * how it is presented in iso-8859-1.
         *
         * So the browser behaves correctly by sending his form input
         * correctly encoded in the advised character encoding. The issue
         * is that the servlet container is typically unable to determine
         * the correct encoding of this form data. By proposal the browser
         * should als declare the used character encoding for his data.
         * But actual browsers omit this information and hence the servlet
         * container is unable to guess the right encoding (Tomcat actually
         * thenalways guesses ISO 8859-1). This results in totally
         * scrumbled up data for all non ISO-8859-1 character encodings.
         * With the block below we tell the servlet container about the
         * character encoding we expect in the browsers request and hence
         * the servlet container can do the correct decoding.
         * This has to be done at very first, otherwise the servlet
         * container will ignore this setting.
         */
        if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding?
            try {
                String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding();
                // We know better about the used character encoding than tomcat
                log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding);
                request.setCharacterEncoding(sessionCharacterEncoding);
            } catch (UnsupportedEncodingException e) {
                log.warn("Problem on applying current session character encoding", e);
            }
        }

        return sessionServlet;
    }
}

From source file:org.wings.session.WingServlet.java

public final SessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response,
        boolean createSessionServlet) throws ServletException {
    final HttpSession httpSession = request.getSession(true);

    // it should be enough to synchronize on the http session object...
    synchronized (httpSession) {
        SessionServlet sessionServlet = null;

        if (httpSession != null) {
            sessionServlet = (SessionServlet) httpSession.getAttribute(lookupName);
        }/* w  w w  .  jav a2  s  .  co m*/

        // Sanity check - maybe this is a stored/deserialized session servlet?
        if (sessionServlet != null && !sessionServlet.isValid()) {
            sessionServlet.destroy();
            sessionServlet = null;
        }

        /*
         * we are only interested in a new session, if the response is
         * not null. If it is null, then we just called getSessionServlet()
         * for lookup purposes and are satisfied, if we don't get anything.
         */
        if (sessionServlet == null) {
            if (createSessionServlet) {
                log.info("no session servlet, create new one");
                sessionServlet = newSession(request, response);
                httpSession.setAttribute(lookupName, sessionServlet);
            } else {
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder().append("session id: ")
                    .append(request.getRequestedSessionId()).append(", created at: ")
                    .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                            .format(new java.util.Date(httpSession.getCreationTime())))
                    .append(", identified via:")
                    .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "")
                    .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ")
                    .append(httpSession.getMaxInactiveInterval()).append("s ");
            log.debug(message.toString());
            //log.debug("session valid " + request.isRequestedSessionIdValid());
            //log.debug("session httpsession id " + httpSession.getId());
            //log.debug("session httpsession new " + httpSession.isNew());
            //log.debug("session last accessed at " +
            //        new java.util.Date(httpSession.getLastAccessedTime()));
            //log.debug("session expiration timeout (s) " +
            //        httpSession.getMaxInactiveInterval());
            //log.debug("session contains wings session " +
            //        (httpSession.getAttribute(lookupName) != null));
        }

        sessionServlet.getSession().getExternalizeManager().setResponse(response);

        /* Handling of the requests character encoding.
         * --------------------------------------------
         * The following block is needed for a correct handling of
         * non-ISO-8859-1 data:
         *
         * Using LocaleCharacterSet and/or charset.properties we can
         * advise the client to use i.e. UTF-8 as character encoding.
         * Once told the browser consequently also encodes his requests
         * in the choosen characterset of the sings session. This is
         * achieved by adding the HTML code
         * <meta http-equiv="Content-Type" content="text/html;charset="<charset>">
         * to the generated pages.
         *
         * If the user hasn't overridden the encoding in their browser,
         * then all form data (e.g. mueller) is submitted with data encoded
         * like m%C3%BCller because byte pair C3 BC is how the german
         * u-umlaut is represented in UTF-8. If the form is
         * iso-8859-1 encoded then you get m%FCller, because byte FC is
         * how it is presented in iso-8859-1.
         *
         * So the browser behaves correctly by sending his form input
         * correctly encoded in the advised character encoding. The issue
         * is that the servlet container is typically unable to determine
         * the correct encoding of this form data. By proposal the browser
         * should als declare the used character encoding for his data.
         * But actual browsers omit this information and hence the servlet
         * container is unable to guess the right encoding (Tomcat actually
         * thenalways guesses ISO 8859-1). This results in totally
         * scrumbled up data for all non ISO-8859-1 character encodings.
         * With the block below we tell the servlet container about the
         * character encoding we expect in the browsers request and hence
         * the servlet container can do the correct decoding.
         * This has to be done at very first, otherwise the servlet
         * container will ignore this setting.
         */
        if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding?
            try {
                String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding();
                // We know better about the used character encoding than tomcat
                log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding);
                request.setCharacterEncoding(sessionCharacterEncoding);
            } catch (UnsupportedEncodingException e) {
                log.warn("Problem on applying current session character encoding", e);
            }
        }

        return sessionServlet;
    }
}