Example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdValid

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

Introduction

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

Prototype

public boolean isRequestedSessionIdValid();

Source Link

Document

Checks whether the requested session ID is still valid.

Usage

From source file:org.openmrs.module.webservices.rest.web.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */// w w  w. ja v a 2 s .  c  om
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // check the IP address first.  If its not valid, return a 403
    if (!RestUtil.isIpAllowed(request.getRemoteAddr())) {
        // the ip address is not valid, set a 403 http error code
        HttpServletResponse httpresponse = (HttpServletResponse) response;
        httpresponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                "IP address '" + request.getRemoteAddr() + "' is not authorized");
    }

    // skip if the session has timed out, we're already authenticated, or it's not an HTTP request
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Session timed out");
        }

        if (!Context.isAuthenticated()) {
            String basicAuth = httpRequest.getHeader("Authorization");
            if (basicAuth != null) {
                // this is "Basic ${base64encode(username + ":" + password)}"
                try {
                    basicAuth = basicAuth.substring(6); // remove the leading "Basic "
                    String decoded = new String(Base64.decodeBase64(basicAuth), Charset.forName("UTF-8"));
                    String[] userAndPass = decoded.split(":");
                    Context.authenticate(userAndPass[0], userAndPass[1]);
                    if (log.isDebugEnabled())
                        log.debug("authenticated " + userAndPass[0]);
                } catch (Exception ex) {
                    // This filter never stops execution. If the user failed to
                    // authenticate, that will be caught later.
                }
            }
        }
    }

    // continue with the filter chain in all circumstances
    chain.doFilter(request, response);
}

From source file:org.regola.security.cas.SingleSignOutFilter.java

private void rigeneraSessione(HttpServletRequest request) {
    HttpSession oldSession = request.getSession(false);

    HashMap<String, Object> tmp = new HashMap<String, Object>();

    if (oldSession != null) {

        Enumeration enumer = oldSession.getAttributeNames();

        while (enumer.hasMoreElements()) {

            String s = (String) enumer.nextElement();

            tmp.put(s, oldSession.getAttribute(s));

        }/*from  w ww.ja v  a  2s . co  m*/

        log.debug("Sessione " + oldSession.getId() + " valida? " + request.isRequestedSessionIdValid());
        oldSession.invalidate();

    }

    HttpSession newSession = request.getSession(true);

    log.debug("E adesso sessione " + newSession.getId() + " valida? " + request.isRequestedSessionIdValid());

    for (Map.Entry<String, Object> entry : tmp.entrySet()) {

        newSession.setAttribute(entry.getKey(), entry.getValue());

    }
}

From source file:org.springframework.security.web.authentication.session.AbstractSessionFixationProtectionStrategy.java

/**
 * Called when a user is newly authenticated.
 * <p>// ww w.  ja  v  a2s  .com
 * If a session already exists, and matches the session Id from the client, a new
 * session will be created, and the session attributes copied to it (if
 * {@code migrateSessionAttributes} is set). If the client's requested session Id is
 * invalid, nothing will be done, since there is no need to change the session Id if
 * it doesn't match the current session.
 * <p>
 * If there is no session, no action is taken unless the {@code alwaysCreateSession}
 * property is set, in which case a session will be created if one doesn't already
 * exist.
 */
public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) {
    boolean hadSessionAlready = request.getSession(false) != null;

    if (!hadSessionAlready && !alwaysCreateSession) {
        // Session fixation isn't a problem if there's no session

        return;
    }

    // Create new session if necessary
    HttpSession session = request.getSession();

    if (hadSessionAlready && request.isRequestedSessionIdValid()) {

        String originalSessionId;
        String newSessionId;
        Object mutex = WebUtils.getSessionMutex(session);
        synchronized (mutex) {
            // We need to migrate to a new session
            originalSessionId = session.getId();

            session = applySessionFixation(request);
            newSessionId = session.getId();
        }

        if (originalSessionId.equals(newSessionId)) {
            logger.warn(
                    "Your servlet container did not change the session ID when a new session was created. You will"
                            + " not be adequately protected against session-fixation attacks");
        }

        onSessionChange(originalSessionId, session, authentication);
    }
}

From source file:org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy.java

/**
 * Called when a user is newly authenticated.
 * <p>/*w  ww . j av a 2s  .c  om*/
 * If a session already exists, and matches the session Id from the client, a new session will be created, and the
 * session attributes copied to it (if {@code migrateSessionAttributes} is set).
 * If the client's requested session Id is invalid, nothing will be done, since there is no need to change the
 * session Id if it doesn't match the current session.
 * <p>
 * If there is no session, no action is taken unless the {@code alwaysCreateSession} property is set, in which
 * case a session will be created if one doesn't already exist.
 */
public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) {
    boolean hadSessionAlready = request.getSession(false) != null;

    if (!hadSessionAlready && !alwaysCreateSession) {
        // Session fixation isn't a problem if there's no session

        return;
    }

    // Create new session if necessary
    HttpSession session = request.getSession();

    if (hadSessionAlready && request.isRequestedSessionIdValid()) {
        // We need to migrate to a new session
        String originalSessionId = session.getId();

        if (logger.isDebugEnabled()) {
            logger.debug("Invalidating session with Id '" + originalSessionId + "' "
                    + (migrateSessionAttributes ? "and" : "without") + " migrating attributes.");
        }

        Map<String, Object> attributesToMigrate = extractAttributes(session);

        session.invalidate();
        session = request.getSession(true); // we now have a new session

        if (logger.isDebugEnabled()) {
            logger.debug("Started new session: " + session.getId());
        }

        if (originalSessionId.equals(session.getId())) {
            logger.warn(
                    "Your servlet container did not change the session ID when a new session was created. You will"
                            + " not be adequately protected against session-fixation attacks");
        }

        transferAttributes(attributesToMigrate, session);

        onSessionChange(originalSessionId, session, authentication);
    }
}

From source file:org.structr.rest.auth.SessionHelper.java

public static Principal checkSessionAuthentication(final HttpServletRequest request) throws FrameworkException {

    String requestedSessionId = request.getRequestedSessionId();
    String sessionId = null;//from  w w  w  .j a  v  a2 s .c  o m

    logger.debug("0. Requested session id: " + requestedSessionId + ", request says is valid? "
            + request.isRequestedSessionIdValid());

    //HttpSession session       = request.getSession(false);
    boolean isNotTimedOut = false;

    if (requestedSessionId == null) {

        logger.debug("1b. Empty requested session id, creating a new one.");

        // No session id requested => create new session
        SessionHelper.newSession(request);

        // Store info in request that session is new => saves us a lookup later
        request.setAttribute(SESSION_IS_NEW, true);

        // we just created a totally new session, there can't
        // be a user with this session ID, so don't search.
        return null;

    } else {

        requestedSessionId = getShortSessionId(requestedSessionId);

        // Existing session id, check if we have an existing session
        if (request.getSession(false) != null) {

            logger.debug("1a. Requested session id without worker id suffix: " + requestedSessionId);

            sessionId = request.getSession(false).getId();
            logger.debug("2a. Current session id: " + sessionId);

            if (sessionId.equals(requestedSessionId)) {

                logger.debug("3a. Current session id equals requested session id");
            } else {

                logger.debug("3b. Current session id does not equal requested session id.");
            }

        } else {

            logger.debug("2b. Current session is null.");

            // Try to find session in session cache
            if (getSessionBySessionId(requestedSessionId) == null) {

                // Not found, create new
                SessionHelper.newSession(request);
                logger.debug("3a. Created new session");

                // remove session ID without session
                SessionHelper.clearSession(requestedSessionId);
                logger.debug("4. Cleared unknown session " + requestedSessionId);

                // we just created a totally new session, there can't
                // be a user with this session ID, so don't search.
                return null;

            } else {
                logger.debug("3b. Session with requested id " + requestedSessionId + " found, continuing.");

                sessionId = requestedSessionId;

            }

        }

        if (SessionHelper.isSessionTimedOut(request.getSession(false))) {

            isNotTimedOut = false;

            // invalidate session
            SessionHelper.invalidateSession(sessionId);

            // remove invalid session ID
            SessionHelper.clearSession(sessionId);

            logger.debug("4a. Cleared timed-out session " + sessionId);

            SessionHelper.newSession(request);
            // we just created a totally new session, there can't
            // be a user with this session ID, so don't search.
            return null;

        } else {

            logger.debug("4b. Session " + sessionId + " is not timed-out.");

            isNotTimedOut = true;
        }
    }

    if (isNotTimedOut) {

        final Principal user = AuthHelper.getPrincipalForSessionId(sessionId);
        //logger.debug("Valid session found: {}, last accessed {}, authenticated with user {}", new Object[]{session, session.getLastAccessedTime(), user});

        return user;

    } else {

        final Principal user = AuthHelper.getPrincipalForSessionId(sessionId);
        if (user != null) {

            //logger.info("Timed-out session: {}, last accessed {}, authenticated with user {}", new Object[]{session, (session != null ? session.getLastAccessedTime() : ""), user});
            logger.debug("Logging out user {}", new Object[] { user });
            AuthHelper.doLogout(request, user);
            try {
                request.logout();
            } catch (Throwable t) {
            }
        }

        SessionHelper.newSession(request);

        return null;
    }
}

From source file:org.viafirma.cliente.filter.AutentifacionViafirmaFilter.java

/**
 * Protege la url indicada . redireccionando a viafirma si el usuario no esta autenticado.
 * Nota: Este mtodo no se debe invocar directamente, para mas informacin consultar:
 * http://www.viafirma.org/api_cliente.html
 * //from w  ww  .  jav a2 s .  co m
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    // Comprobamos si nos encontramos ante una peticin yadis ( Sin sessin
    // del usuario)
    if (!request.isRequestedSessionIdValid()) {
        log.debug(
                "No hay sessin, consideramos que es una peticin yadis. Se requiere que la validacin Relying Party Discovery");
        // response.setHeader("X-XRDS-Location",
        // request.getSession().getServletContext
        // ().getAttribute(Constantes.PARAM_URL_APLICACION)+"/yadis.jsp")
        response.sendError(401);
        return;
    }

    // Si el usuario no esta autenticado iniciamos el proceso de
    // autenticacin
    if (!isAutenticado(request, response)) {

        // Recuperamos el identificador del usuario
        // autenticamos al usuario utilizando Viafirma
        // 1- Obtenemos una instancia del API cliente.
        ViafirmaClient cliente = ViafirmaClientFactory.getInstance();

        // si el usuario no esta autenticado hay dos posibilidades
        // 1.-que justo en este momento estemos volviendo de Viafirma con
        // los datos del protocolo OpenID. y
        // procesemos el certificado para logarnos
        // 2.- Que tengamos aun que ir a Viafirma

        // para saber si estamos retornando de Viafirma, busco el
        // parametro openId( que es la marca de identificacin de que
        // estamos volviendo de Viafirma
        try {
            if (cliente.isResponseAuthentication(request)) {
                // La autenticacin ya se ha producido
                // Recuperamos los datos recuperados del certificado del
                // usuario.
                Map<String, String> result = cliente.processResponseAuthentication(request, response);
                // metemos el resultado en request para que pueda ser
                // pintado en a siguiente pgina.
                request.setAttribute("result", result);
                // digerimos el map de resultado para generar un usuarioVO
                UsuarioGenericoViafirma usuario = cliente.digest(result);

                // indicamos a la aplicacin cliente que la autenticacin se
                // ha realizado correctamente.
                autenticarAplicacion(chain, request, response, usuario);
            } else if (cliente.isResponseCancel(request)) {
                // el usuario ya inicio la autenticacin pero cancelo el
                // proceso.
                log.info("Autenticacin cancelada por el usuario.");
                sendError("Autenticacin cancelada por el usuario", "", request, response);
            } else {
                // an no hay datos, iniciamos la autenticacin
                cliente.autenticar(request, response);
            }
        } catch (InternalException e) {
            // No se ha podido redireccionar al usuario para que realice la
            // autenticacin.
            // redireccionamos a la pgina de error de autenticacin.
            log.warn(e.getMessage());
            sendError(e.getMessage(), "" + e.getCodigoError().getCodigo(), request, response);
        }
    } else {
        // el certificado y el usuario esta correcto. y el usuario esta ya
        // logado. OK!!
        chain.doFilter(request, response);
    }

}

From source file:org.viafirma.cliente.filter.FirmaViafirmaFilter.java

/**
 * Filtro para la firma de ficheros WEB. El fuincionamiento es el siguiente.
 * Protege una determinada url, garantizando que antes de llegar a esa url
 * se ha firmado correctamente un fichero subido previamente al servidor
 *///from   w  w  w.  j ava2 s  . co m
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    // Comprobamos si nos encontramos ante una peticin yadis ( Sin sessin
    // del usuario)
    if (!request.isRequestedSessionIdValid()) {
        log.debug(
                "No hay sessin, consideramos que es una peticin yadis. Se requiere que la validacin Relying Party Discovery");
        // response.setHeader("X-XRDS-Location",
        // request.getSession().getServletContext
        // ().getAttribute(Constantes.PARAM_URL_APLICACION)+"/yadis.jsp")
        response.sendError(401);
        return;
    }

    boolean firmaActivada = isEnable(request);
    // comprobamos si la firma de ficheros esta o no desabilitada
    if (!firmaActivada) {
        log.debug("Firma de ficheros no habilitada, permitimos el paso");
        chain.doFilter(request, response);
    } else {
        try {
            // 1- Obtenemos una instancia del API cliente.
            ViafirmaClient cliente = ViafirmaClientFactory.getInstance();

            // si estamos firmando un documento, hay dos posiblidades.
            // 1.-que justo en este momento estemos volviendo de Viafirma
            // con los datos del protocolo OpenID. y
            // procesemos el resultado de la firma.
            // 2.- Que tengamos aun que ir a Viafirma y enviar el documento
            // a firmar.

            // para saber si estamos retornando de Viafirma, busco el
            // parametro openId( que es la marca de identificacin de que
            // estamos volviendo de Viafirma

            if (cliente.isResponseAuthentication(request)) {
                // La firma ya se ha producido
                // Recuperamos los datos recuperados rel resultado de la
                // firma.
                Map<String, String> result = cliente.processResponseAuthentication(request, response);
                // metemos el resultado en request para que pueda ser
                // pintado en a siguiente pgina.
                request.setAttribute("result", result);

                // digerimos el resultado para obtener la informacin de la
                // firma
                FirmaInfoViafirma info = cliente.digestFirma(result);

                // indicamos a la aplicacin cliente que la autenticacin se
                // ha realizado correctamente.
                procesarResultado(chain, request, response, info);
            } else {
                // // an no hay datos, iniciamos el proceso de firma

                // 1.- Recuperamos el fichero que deseamos firmar
                FicheroVO fichero = getFicheroAfirmar(request);
                // 2.- Enviamos el fichero a la plataforma
                String idFirma = cliente.prepareFirma(fichero.getNombre(),
                        TypeFile.getFromFileName(fichero.getNombre()), fichero.getBytes());
                log.debug("Preparado para firmar el fichero con el identificador: " + idFirma);
                // enviamos al usuario a viafirma.
                cliente.solicitarFirma(idFirma, request, response);
            }
        } catch (InternalException e) {
            // No se ha podido redireccionar al usuario para que realice la
            // autenticacin.
            // redireccionamos a la pgina de error de autenticacin.
            log.warn(e.getMessage());
            request.getSession().setAttribute("error", e.getMessage());
            request.getSession().setAttribute("codError", e.getCodigoError());
            request.getRequestDispatcher(ConfigUtil.getInstance().getUriError()).forward(request, response);
        }
    }
}

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

/**
 * Verarbeitet Informationen vom Browser:
 * <UL>/*ww w  .  jav a2s  .c  om*/
 * <LI> setzt Locale
 * <LI> Dispatch Get Parameter
 * <LI> feuert Form Events
 * </UL>
 * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet
 * werden kann.
 */
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) {
    // Special case: You double clicked i.e. a "logout button"
    // First request arrives, second is on hold. First invalidates session and sends redirect as response,
    // but browser ignores and expects response in second request. But second request has longer a valid session.
    if (session == null) {
        try {
            response.sendRedirect(exitSessionWorkaround != null ? exitSessionWorkaround : "");
            return;
        } catch (IOException e) {
            log.info("Session exit workaround failed to to IOException (triple click?)");
        }
    }

    SessionManager.setSession(session);
    session.setServletRequest(req);
    session.setServletResponse(response);

    session.fireRequestEvent(SRequestEvent.REQUEST_START);

    // in case, the previous thread did not clean up.
    SForm.clearArmedComponents();

    Device outputDevice = null;

    ReloadManager reloadManager = session.getReloadManager();

    try {
        /*
         * The tomcat 3.x has a bug, in that it does not encode the URL
         * sometimes. It does so, when there is a cookie, containing some
         * tomcat sessionid but that is invalid (because, for instance,
         * we restarted the tomcat in-between).
         * [I can't think of this being the correct behaviour, so I assume
         *  it is a bug. ]
         *
         * So we have to workaround this here: if we actually got the
         * session id from a cookie, but it is not valid, we don't do
         * the encodeURL() here: we just leave the requestURL as it is
         * in the properties .. and this is url-encoded, since
         * we had set it up in the very beginning of this session
         * with URL-encoding on  (see WingServlet::newSession()).
         *
         * Vice versa: if the requestedSessionId is valid, then we can
         * do the encoding (which then does URL-encoding or not, depending
         * whether the servlet engine detected a cookie).
         * (hen)
         */
        RequestURL portletRequestURL = null;
        // get the renderResponse
        RenderResponse renderResponse = (RenderResponse) req.getAttribute(Const.REQUEST_ATTR_RENDER_RESPONSE);
        if (renderResponse == null) {
            log.error("WingS-Portlet-Bridge: cant get the request attribute "
                    + Const.REQUEST_ATTR_RENDER_RESPONSE);
        }
        PortletURL actionURL = renderResponse.createActionURL();
        if (req.isRequestedSessionIdValid()) {
            portletRequestURL = new PortletRequestURL(actionURL.toString(),
                    response.encodeURL(actionURL.toString()));
            log.debug("WingS-Portlet-Bridge: created PortletRequestURL " + actionURL.toString());
            // this will fire an event, if the encoding has changed ..
            session.setProperty("request.url", portletRequestURL);
            session.setProperty(Const.WINGS_SESSION_PROPERTY_RENDER_RESPONSE, renderResponse);

            // get the RenderRequest
            RenderRequest renderRequest = (RenderRequest) req.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST);
            if (renderRequest == null) {
                log.error("WingS-Portlet-Bridge: cant get the request attribute "
                        + Const.REQUEST_ATTR_RENDER_REQUEST);
            }
            session.setProperty(Const.WINGS_SESSION_PROPERTY_RENDER_REQUEST, renderRequest);
        }

        if (log.isDebugEnabled()) {
            log.debug("Request URL: " + portletRequestURL);
            log.debug("HTTP header:");
            for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) {
                String header = (String) en.nextElement();
                log.debug("    " + header + ": " + req.getHeader(header));
            }
        }
        handleLocale(req);

        // WingS-Portlet-Bridge: get the Parameter from the map in the request
        // set by the portlet
        Map params = (Map) req.getAttribute(Const.REQUEST_ATTR_PARAMETERS_FROM_ACTION_MAP);

        // The externalizer is able to handle static and dynamic resources
        ExternalizeManager extManager = getSession().getExternalizeManager();
        //WingS-Portlet-Bridge:
        //String pathInfo = req.getPathInfo();                    // Note: Websphere returns <code>null</code> here!
        String pathInfo = null;
        if (params != null) {
            String[] path = (String[]) params.get(Const.REQUEST_PARAM_RESOURCE_AS_PARAM);
            if (path != null)
                pathInfo = path[0];
        }

        if (pathInfo != null && pathInfo.length() > 0) {
            // strip of leading /
            // WingS-Portlet-Bridge:
            // pathInfo = pathInfo.substring(1);
        }

        log.info("WingS-Portlet-Bridge: pathInfo: " + pathInfo);

        // If we have no path info, or the special '_' path info (that should be explained
        // somewhere, Holger), then we deliver the top-level frame of this application.
        String externalizeIdentifier = null;
        if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) {
            externalizeIdentifier = retrieveCurrentRootFrameResource().getId();
            firstRequest = false;
        } else {
            externalizeIdentifier = pathInfo;
        }

        // Retrieve externalized resource
        ExternalizedResource extInfo = extManager.getExternalizedResource(externalizeIdentifier);

        // Special case handling: We request a .html resource of a session which is not accessible.
        // This happens some times and leads to a 404, though it should not be possible.
        if (extInfo == null && pathInfo != null && pathInfo.endsWith(".html")) {
            log.info("Found a request to an invalid .html during a valid session. Redirecting to root frame.");
            response.sendRedirect(retrieveCurrentRootFrameResource().getURL().toString());
            return;
        }

        if (extInfo != null && extInfo.getObject() instanceof UpdateResource) {
            reloadManager.setUpdateMode(true);
        } else {
            reloadManager.setUpdateMode(false);
        }

        // Prior to dispatching the actual events we have to detect
        // their epoch and inform the dispatcher which will then be
        // able to check if the request is valid and processed. If
        // this is not the case, we force a complete page reload.
        String ee = "";
        if (params != null) {
            String[] eeArray = (String[]) params.get("event_epoch");
            if (eeArray != null)
                ee = eeArray[0];
        }
        session.getDispatcher().setEventEpoch(ee);

        // WingS-Portlet-Bridge: Map for the parameters 
        // set by a SPortletAnchor or set in the Portlet
        Map portletParameters = new HashMap();

        // Enumeration en = req.getParameterNames();
        if (params != null) {
            Set paramNames = params.keySet();
            Iterator paramNamesIter = paramNames.iterator();

            Cookie[] cookies = req.getCookies();

            // are there parameters/low level events to dispatch
            if (paramNamesIter.hasNext()) {
                // only fire DISPATCH_START if we have parameters to dispatch
                session.fireRequestEvent(SRequestEvent.DISPATCH_START);

                if (cookies != null) {
                    //dispatch cookies
                    for (int i = 0; i < cookies.length; i++) {
                        Cookie cookie = cookies[i];
                        String paramName = cookie.getName();
                        String value = cookie.getValue();

                        if (log.isDebugEnabled())
                            log.debug("dispatching cookie " + paramName + " = " + value);

                        session.getDispatcher().dispatch(paramName, new String[] { value });
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug("Parameters:");
                    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
                        String paramName = (String) e.nextElement();
                        StringBuilder param = new StringBuilder();
                        param.append("    ").append(paramName).append(": ");
                        final String[] values = req.getParameterValues(paramName);
                        param.append(values != null ? Arrays.toString(values) : "null");
                        log.debug(param);
                    }
                }

                while (paramNamesIter.hasNext()) {
                    String paramName = (String) paramNamesIter.next();
                    String[] values = (String[]) params.get(paramName);

                    // We do not need to dispatch the event epoch and the XHR request ID
                    if (paramName.equals("event_epoch") || paramName.equals("_xhrID")) {
                        continue;
                    }

                    String value = values[0];

                    // Split the values of the event trigger
                    if (paramName.equals("event_trigger")) {
                        int pos = value.indexOf('|');
                        paramName = value.substring(0, pos);
                        values = new String[] { value.substring(pos + 1) };
                    }

                    // Handle form submit via default button
                    if (paramName.equals("default_button")) {
                        if (value.equals("undefined")) {
                            continue;
                        } else {
                            paramName = values[0];
                            values = new String[] { "1" };
                        }
                    }

                    // WingS-Portlet-Bridge: get the portlet parameters
                    if (paramName.startsWith(Const.WINGS_PORTLET_URL_CODE_STRING)) {
                        log.info("WingS-Portlet-Bridge: getting portlet parameter " + paramName + " = "
                                + Arrays.asList(values));
                        portletParameters.put(PortletParameterCodec.decode(paramName), values);
                    } else {
                        if (log.isDebugEnabled())
                            log.debug("dispatching " + paramName + " = " + Arrays.asList(values));
                        session.getDispatcher().dispatch(paramName, values);
                    }

                }

                SForm.fireEvents();

                // only fire DISPATCH DONE if we have parameters to dispatch
                session.fireRequestEvent(SRequestEvent.DISPATCH_DONE);
            }
        }

        //WingS-Portlet-Bridge: store the portlet parameters in the session
        session.setProperty(Const.WINGS_SESSION_PROPERTY_PORTLET_PARAMETER_MAP, portletParameters);

        session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST);
        session.getDispatcher().invokeRunnables();

        // WingS-Portlet-Bridge: fires events if the window state has changed
        session.fireWindowStateEvents();
        // WingS-Portlet-Bridge: fires events for the new portlet parameters
        session.fireNewPortletParameters();

        // if the user chose to exit the session as a reaction on an
        // event, we got an URL to redirect after the session.
        /*
         * where is the right place?
         * The right place is
         *    - _after_ we processed the events
         *        (e.g. the 'Pressed Exit-Button'-event or gave
         *         the user the chance to exit this session in the custom
         *         processRequest())
         *    - but _before_ the rendering of the page,
         *      because otherwise an redirect won't work, since we must
         *      not have sent anything to the output stream).
         */
        if (session.getExitAddress() != null) {

            try {
                session.firePrepareExit();
                session.fireRequestEvent(SRequestEvent.REQUEST_END);

                String redirectAddress;
                if (session.getExitAddress().length() > 0) {
                    // redirect to user requested URL.
                    redirectAddress = session.getExitAddress();
                } else {
                    // redirect to a fresh session.
                    redirectAddress = req.getRequestURL().toString();
                }
                req.getSession().invalidate(); // calls destroy implicitly
                response.sendRedirect(redirectAddress);
                exitSessionWorkaround = redirectAddress;
                return;
            } catch (ExitVetoException ex) {
                session.exit(null);
            } // end of try-catch
        }

        if (session.getRedirectAddress() != null) {
            handleRedirect(response);
            return;
        }

        reloadManager.notifyCGs();
        reloadManager.invalidateFrames();

        // TODO ResourceMapper
        ResourceMapper mapper = session.getResourceMapper();
        if (extInfo == null && mapper != null) {
            //wings-Portlet-Bridge:
            //                Resource res = mapper.mapResource(req.getPathInfo());
            Resource res = mapper.mapResource(pathInfo);
            if (res != null) {
                extInfo = extManager.getExternalizedResource(res.getId());
            }
        }

        if (extInfo != null) {
            outputDevice = DeviceFactory.createDevice(extInfo);
            session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo);

            long startTime = System.currentTimeMillis();
            extManager.deliver(extInfo, response, outputDevice);
            long endTime = System.currentTimeMillis();
            log.debug("------------------------- Time needed for rendering: " + (endTime - startTime)
                    + " ms -------------------------\n");

            session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo);
        } else {
            handleUnknownResourceRequested(req, response);
        }

    } catch (Throwable e) {
        log.error("Uncaught Exception", e);
        handleException(response, e);
    } finally {
        if (session != null) {
            session.fireRequestEvent(SRequestEvent.REQUEST_END);
        }

        if (outputDevice != null) {
            try {
                outputDevice.close();
            } catch (Exception e) {
            }
        }

        /*
         * the session might be null due to destroy().
         */
        if (session != null) {
            reloadManager.clear();
            session.setServletRequest(null);
            session.setServletResponse(null);
        }

        // make sure that the session association to the thread is removed
        // from the SessionManager
        SessionManager.removeSession();
        SForm.clearArmedComponents();
    }
}

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

/**
 * Verarbeitet Informationen vom Browser:
 * <UL>/*from   w w  w  . j  a va2s .c  o  m*/
 * <LI> setzt Locale
 * <LI> Dispatch Get Parameter
 * <LI> feuert Form Events
 * </UL>
 * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet
 * werden kann.
 */
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) {
    // Special case: You double clicked i.e. a "logout button"
    // First request arrives, second is on hold. First invalidates session and sends redirect as response,
    // but browser ignores and expects response in second request. But second request has longer a valid session.
    if (session == null) {
        try {
            response.sendRedirect(exitSessionWorkaround != null ? exitSessionWorkaround : "");
            return;
        } catch (IOException e) {
            log.info("Session exit workaround failed to to IOException (triple click?)");
        }
    }

    SessionManager.setSession(session);
    session.setServletRequest(req);
    session.setServletResponse(response);

    session.fireRequestEvent(SRequestEvent.REQUEST_START);

    // in case, the previous thread did not clean up.
    SForm.clearArmedComponents();

    Device outputDevice = null;

    ReloadManager reloadManager = session.getReloadManager();

    try {
        /*
         * The tomcat 3.x has a bug, in that it does not encode the URL
         * sometimes. It does so, when there is a cookie, containing some
         * tomcat sessionid but that is invalid (because, for instance,
         * we restarted the tomcat in-between).
         * [I can't think of this being the correct behaviour, so I assume
         *  it is a bug. ]
         *
         * So we have to workaround this here: if we actually got the
         * session id from a cookie, but it is not valid, we don't do
         * the encodeURL() here: we just leave the requestURL as it is
         * in the properties .. and this is url-encoded, since
         * we had set it up in the very beginning of this session
         * with URL-encoding on  (see WingServlet::newSession()).
         *
         * Vice versa: if the requestedSessionId is valid, then we can
         * do the encoding (which then does URL-encoding or not, depending
         * whether the servlet engine detected a cookie).
         * (hen)
         */
        RequestURL requestURL = null;
        if (req.isRequestedSessionIdValid()) {
            requestURL = new RequestURL("", getSessionEncoding(response));
            // this will fire an event, if the encoding has changed ..
            session.setProperty("request.url", requestURL);
        }

        if (log.isDebugEnabled()) {
            log.debug("Request URL: " + requestURL);
            log.debug("HTTP header:");
            for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) {
                String header = (String) en.nextElement();
                log.debug("    " + header + ": " + req.getHeader(header));
            }
        }
        handleLocale(req);

        // The pathInfo addresses the resource
        String pathInfo = req.getPathInfo(); // Note: Websphere returns <code>null</code> here!
        if (pathInfo != null && pathInfo.length() > 0) {
            // strip of leading /
            pathInfo = pathInfo.substring(1);
        }
        if (log.isDebugEnabled())
            log.debug("pathInfo: " + pathInfo);

        ResourceMapper mapper = session.getResourceMapper();

        // The externalizer is able to handle static and dynamic resources
        ExternalizeManager extManager = getSession().getExternalizeManager();

        ExternalizedResource extInfo;
        Resource resource;
        if (pathInfo == null || pathInfo.length() == 0)
            extInfo = extManager.getExternalizedResource(retrieveCurrentRootFrameResource().getId());
        else if (mapper != null && (resource = mapper.mapResource(pathInfo)) != null)
            extInfo = extManager.getExternalizedResource(resource.getId());
        else if (firstRequest) {
            extInfo = extManager.getExternalizedResource(retrieveCurrentRootFrameResource().getId());
        } else
            extInfo = extManager.getExternalizedResource(pathInfo);

        firstRequest = false;

        // Special case handling: We request a .html resource of a session which is not accessible.
        // This happens some times and leads to a 404, though it should not be possible.
        if (extInfo == null && pathInfo != null && (pathInfo.endsWith(".html") || pathInfo.endsWith(".xml"))) {
            log.info("Got a request to an invalid .html during a valid session .. redirecting to root frame.");
            response.sendRedirect("");
            return;
        }

        if (extInfo != null && extInfo.getObject() instanceof UpdateResource) {
            reloadManager.setUpdateMode(true);

            String eventEpoch = req.getParameter("event_epoch");
            UpdateResource updateResource = (UpdateResource) extInfo.getObject();
            updateResource.getFrame().getEventEpoch();

            if (eventEpoch != null && !eventEpoch.equals(updateResource.getFrame().getEventEpoch())) {
                reloadManager.setUpdateMode(false);
            }
        } else {
            reloadManager.setUpdateMode(false);
        }

        // Prior to dispatching the actual events we have to detect
        // their epoch and inform the dispatcher which will then be
        // able to check if the request is valid and processed. If
        // this is not the case, we force a complete page reload.
        LowLevelEventDispatcher eventDispatcher = session.getDispatcher();
        eventDispatcher.setEventEpoch(req.getParameter("event_epoch"));

        Enumeration en = req.getParameterNames();
        final Cookie[] cookies = req.getCookies();
        final Collection<Cookie> cookiesToDispatch = new ArrayList<Cookie>();

        // handle debug.cookie - read it every time. 
        session.removeProperty("debug.cookie");
        if (cookies != null) {
            //handle cookies
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                String paramName = cookie.getName();

                if ("DEBUG".equals(paramName)) {
                    // Cookies have a limited length, therefore we copy
                    // them trustingly into the session.

                    // Use a Tokenizer for performance.
                    String paramValue = URLDecoder.decode(cookie.getValue(), "ISO-8859-1");
                    StringTokenizer tokenizer = new StringTokenizer(paramValue, "|");
                    String[] values = new String[tokenizer.countTokens()];
                    for (int j = 0; j < values.length; j++) {
                        values[j] = tokenizer.nextToken();
                    }
                    session.setProperty("debug.cookie", values);
                } else {
                    cookiesToDispatch.add(cookie);
                }
            }
        }

        // are there parameters/low level events to dispatch
        if (en.hasMoreElements()) {
            // only fire DISPATCH_START if we have parameters to dispatch
            session.fireRequestEvent(SRequestEvent.DISPATCH_START);

            eventDispatcher.startLowLevelEventPhase();
            if (cookiesToDispatch != null) {
                //dispatch cookies
                for (Cookie cookie : cookiesToDispatch) {
                    String paramName = cookie.getName();
                    String value = cookie.getValue();

                    if (log.isDebugEnabled())
                        log.debug("dispatching cookie " + paramName + " = " + value);

                    eventDispatcher.dispatch(paramName, new String[] { value });
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("Parameters:");
                for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
                    String paramName = (String) e.nextElement();
                    StringBuilder param = new StringBuilder();
                    param.append("    ").append(paramName).append(": ");
                    final String[] values = req.getParameterValues(paramName);
                    param.append(values != null ? Arrays.toString(values) : "null");
                    log.debug(param);
                }
            }

            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String[] values = req.getParameterValues(paramName);

                //We do not need to dispatch the event epoch since it is already
                // handled a few lines above. Furthermore we will not dispatch any
                // names that start with an '_' (e.g. _xhrId or parts of XCalendar).
                if (paramName.equals("event_epoch") || paramName.startsWith("_") || paramName.equals("comet")
                        || paramName.equals("polling")) {
                    continue;
                }

                String value = values[0];

                // Split the values of the event trigger
                if (paramName.equals("event_trigger")) {
                    int pos = value.indexOf('|');
                    paramName = value.substring(0, pos);
                    values = new String[] { value.substring(pos + 1) };
                }

                // Handle form submit via default button
                if (paramName.equals("default_button")) {
                    if (value.equals("undefined")) {
                        continue;
                    } else {
                        paramName = values[0];
                        values = new String[] { "1" };
                    }
                }

                if (log.isDebugEnabled())
                    log.debug("dispatching " + paramName + " = " + Arrays.asList(values));

                eventDispatcher.dispatch(paramName, values);
            }
            eventDispatcher.endLowLevelEventPhase();

            SForm.fireEvents();

            // only fire DISPATCH DONE if we have parameters to dispatch
            session.fireRequestEvent(SRequestEvent.DISPATCH_DONE);
        }

        session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST);
        eventDispatcher.invokeRunnables();

        // if the user chose to exit the session as a reaction on an
        // event, we got an URL to redirect after the session.
        /*
         * where is the right place?
         * The right place is
         *    - _after_ we processed the events
         *        (e.g. the 'Pressed Exit-Button'-event or gave
         *         the user the chance to exit this session in the custom
         *         processRequest())
         *    - but _before_ the rendering of the page,
         *      because otherwise an redirect won't work, since we must
         *      not have sent anything to the output stream).
         */
        if (session.getExitAddress() != null) {
            try {
                session.firePrepareExit();
                session.fireRequestEvent(SRequestEvent.REQUEST_END);

                String redirectAddress;
                if (session.getExitAddress().length() > 0) {
                    // redirect to user requested URL.
                    redirectAddress = session.getExitAddress();
                } else {
                    // redirect to a fresh session.
                    redirectAddress = req.getRequestURL().toString();
                    if (pathInfo != null) { // Websphere pathinfo is null
                        // Make sure that the redirect address doesn't contain any path info.
                        redirectAddress = redirectAddress.substring(0,
                                redirectAddress.length() - pathInfo.length());
                    }
                }

                exitSessionWorkaround = redirectAddress;

                if (reloadManager.isUpdateMode()) {
                    ScriptListener listener = new JavaScriptListener(null, null,
                            "location.href='" + redirectAddress + "'");
                    ScriptManager.getInstance().addScriptListener(listener);
                    req.getSession().invalidate(); // calls destroy implicitly
                } else {
                    response.sendRedirect(redirectAddress);
                    req.getSession().invalidate(); // calls destroy implicitly
                    return;
                }
            } catch (ExitVetoException ex) {
                session.exit(null);
            } // end of try-catch
        }

        if (session.getRedirectAddress() != null) {
            handleRedirect(response);
            return;
        }

        reloadManager.invalidateFrames();

        if (extInfo != null) {
            outputDevice = DeviceFactory.createDevice(extInfo);
            try {
                session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo);

                long startTime = System.currentTimeMillis();
                extManager.deliver(extInfo, response, outputDevice);
                if (log.isDebugEnabled()) {
                    log.debug("Rendering time: " + (System.currentTimeMillis() - startTime) + " ms");
                }

            } finally {
                session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo);
            }
        } else {
            handleUnknownResourceRequested(req, response);
        }

    } catch (Throwable e) {
        log.error("Uncaught Exception", e);
        handleException(response, e);
    } finally {
        if (session != null) {
            session.fireRequestEvent(SRequestEvent.REQUEST_END);
        }

        if (outputDevice != null) {
            try {
                outputDevice.close();
            } catch (Exception e) {
            }
        }

        /*
         * the session might be null due to destroy().
         */
        if (session != null) {
            reloadManager.clear();
            session.setServletRequest(null);
            session.setServletResponse(null);
        }

        // make sure that the session association to the thread is removed
        // from the SessionManager
        SessionManager.removeSession();
        SForm.clearArmedComponents();
    }
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.IWAAuthenticationUtil.java

/**
 * Invalide a session. This is to prevent session fixation attacks
 *
 * @param request//from  w  ww . j  a v  a  2  s . co  m
 */
public static void invalidateSession(HttpServletRequest request) {
    if (request.isRequestedSessionIdValid()) {
        // invalidate the session. ie. clear all attributes
        request.getSession().invalidate();
        // create a new session thereby creating a new jSessionID
        request.getSession(true);
    }
}