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:de.itsvs.cwtrpc.security.RpcSessionManagementFilter.java

protected boolean processUnauthenticatedRequest(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    if ((request.getRequestedSessionId() != null) && !request.isRequestedSessionIdValid()) {
        log.debug("Request does not contain a valid session ID");

        getInvalidSessionRedirectStrategy().sendRedirect(request, response, getInvalidSessionUrl());
        return false;
    }/*  ww w.  ja v  a 2 s.com*/

    return true;
}

From source file:com.huateng.ebank.framework.session.SessionManager.java

public boolean isValid(HttpServletRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("isValid(HttpServletRequest) - start"); //$NON-NLS-1$
    }//ww w .j  av  a  2  s. c  om

    boolean returnboolean = req.isRequestedSessionIdValid();
    if (logger.isDebugEnabled()) {
        logger.debug("isValid(HttpServletRequest) - end"); //$NON-NLS-1$
    }
    return returnboolean;
}

From source file:eu.smartenit.unada.web.ui.UnadaSessionBean.java

/**
 * The init() method that initializes the ConfigurationBean.
 * It checks for valid sessions, retrieves user's token and checks 
 * whether he is the machine owner and also retrieves stored 
 * uNaDa configuration parameters.//  w w  w. j a  va2s  .c  om
 * 
 */
@PostConstruct
public void init() {
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();

    boolean validSession = req.getRequestedSessionId() != null && !req.isRequestedSessionIdValid();

    boolean noFacebook = false;
    try {
        noFacebook = (Boolean) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap()
                .get("noFacebook");
        if (noFacebook) {
            name = "admin";
            return;
        }
    } catch (Exception e) {
        // do nothing
    }

    // check if session has expired
    if (!validSession) {
        String error = req.getParameter("error_reason");
        if (error != null) {
            redirectToLoginPage();
        }

        String code = req.getParameter("code");
        if (code != null) {
            String token = null;
            try {
                token = retrieveToken(code);
            } catch (Exception e) {
                logger.error("Error while retrieving token: " + e.getMessage());
                redirectToLoginPage();
            }
            if (token != null) {
                Owner owner = DAOFactory.getOwnerDAO().findLast();
                Owner currentUser = getOwner(token);

                if (owner == null) {
                    logger.info("Currently there is no owner for this uNaDa.");
                    try {
                        //insert owner of this unada
                        getExtendedToken(currentUser);
                        DAOFactory.getOwnerDAO().insert(currentUser);

                        //add owner as trusted user and update MAC address
                        TrustedUser trustedUser = new TrustedUser();
                        trustedUser.setFacebookID(currentUser.getFacebookID());
                        String ipAddress = req.getRemoteAddr();
                        trustedUser.setMacAddress(ARP.getArpInstance().execute(ipAddress));
                        DAOFactory.getTrustedUserDAO().insert(trustedUser);

                    } catch (Exception e) {
                        logger.error("Error while inserting new owner and trusted user: " + e.getMessage());
                    }
                } else {
                    logger.info("Current owner id = " + owner.getFacebookID());
                    if (owner.getFacebookID().equals(currentUser.getFacebookID())) {
                        logger.info(
                                "Existing owner successfully logins to the uNaDa. " + "Updating his token.");
                        getExtendedToken(currentUser);
                        DAOFactory.getOwnerDAO().update(currentUser);
                        logger.debug("Updated token = " + currentUser.getOauthToken());

                        //update trusted user and his MAC address
                        /*
                        TrustedUser trustedUser = new TrustedUser();
                        trustedUser.setFacebookID(currentUser.getFacebookID());
                        String ipAddress = req.getRemoteAddr();
                        trustedUser.setMacAddress(ARP.getArpInstance().execute(ipAddress));
                        try {
                        DAOFactory.getTrustedUserDAO().insert(trustedUser);
                        } catch (Exception e) {
                        logger.error("Error while updating trusted user: "
                                + e.getMessage());
                        }
                        */

                    } else {
                        redirectToLoginPage();
                    }
                }
            } else {
                redirectToLoginPage();
            }
        } else {
            redirectToLoginPage();
        }
    }
}

From source file:jp.co.opentone.bsol.linkbinder.view.filter.LoginFilter.java

private boolean isSessionTimeout(HttpServletRequest request) {
    // WebLogic??????null????????null?????
    // ?????????????
    // Tomcat?????null???????ID???
    HttpSession session = request.getSession(false);
    return (session != null || !request.isRequestedSessionIdValid()) && !isLoggedIn(request)
            && hasJsessionId(request);
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*w  w  w.j av a  2s . c om*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

private boolean isSessionIdValid(final HttpServletRequest request) {
    final String postedSessionId = request.getParameter(PARAM_SESSION_ID);
    final String requestedSessionId = request.getRequestedSessionId();
    return requestedSessionId != null && postedSessionId != null && postedSessionId.equals(requestedSessionId)
            && request.isRequestedSessionIdValid();
}

From source file:com.deep.two.authority.impl.FareAbstractSessionFixationProtection.java

/**
 * Called when a user is newly authenticated.
 * <p>/*from   w w w. jav a 2 s.c  o m*/
 * 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) {
    /*String queryString = request.getQueryString();
    String userName = "";
            
    if (queryString != null) {
    int index = queryString.indexOf("userName=");
    if (index != -1) {
        userName = queryString.substring(index + 9);
    }
    } else {
    userName = request.getParameter("j_username");
    }
    HttpSession session = SessionHelper.sessionMap.get(userName);*/

    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(session, 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:de.itsvs.cwtrpc.security.RpcLogoutFilter.java

@Override
protected void process(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final Authentication authentication;
    boolean ok = false;

    authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!CwtRpcUtils.isRpcSessionInvalidationPolicySet(request)) {
        CwtRpcUtils.saveRpcSessionInvalidationPolicy(request,
                createRpcSessionInvalidationPolicy(request, response, authentication));
    } else {/* ww w  . j a  v a 2 s .c o  m*/
        log.debug("RPC session invalidation policy " + "has already been applied.");
    }

    try {
        if (authentication != null) {
            if (log.isDebugEnabled()) {
                log.debug("Logging out user '" + authentication.getName() + "'");
            }

            chain.doFilter(request, response);

            if (getLogoutHandlers() != null) {
                for (LogoutHandler handler : getLogoutHandlers()) {
                    handler.logout(request, response, authentication);
                }
            }
        } else {
            if ((request.getRequestedSessionId() == null) || request.isRequestedSessionIdValid()) {
                log.debug("Request does not belong to " + "an authenticated session");
                getLogoutFailureHandler().onLogoutFailure(request, response,
                        new CwtRpcException("Request does not belong to " + "an authenticated session."));
                return;
            }
            log.debug("Request does not include a valid " + "authentication. It seems to be a result of a "
                    + "session timeout. Sending success response.");
        }

        /*
         * If session has not been invalidated up to now, this is the last
         * possibility to invalidate the session. The logout success hander
         * may send the response to the client. The session should be
         * invalidated before sending the response.
         */
        if (isInvalidateSession()) {
            invalidateSession(request);
        }
        getLogoutSuccessHandler().onLogoutSuccess(request, response, authentication);

        ok = true;
    } finally {
        if (!ok && isInvalidateSession()) {
            invalidateSession(request);
        }
    }
}

From source file:com.gtwm.pb.servlets.AppController.java

/**
 * Create an instance of ViewMethods to provide the UI with the necessary
 * functionality, and return the requested template.
 * //  w  w  w. ja va  2 s . c  om
 *         TODO: This method obviously doesn't throw any exceptions for a
 *         reason, presumably we always want to return a template whatever
 *         happens. Check out whether there's a better way of doing things
 *         though
        
 * @param exceptionCaught
 *            An exception thrown by handleRequest. Pass null if none. This
 *            will be saved in ViewMethods to allow the UI to find out what
 *            went wrong
 * @return The template requested, ready to parse by the UI
 * 
 */
private Template getUserInterfaceTemplate(HttpServletRequest request, HttpServletResponse response,
        String templateName, Context context, HttpSession session, SessionDataInfo sessionData,
        Exception exceptionCaught, List<FileItem> multipartItems) {
    // template ('return' parameter) *must* be specified
    if (templateName == null) {
        logger.error("No template specified. Please add 'return=<i>templatename</i>' to the HTTP request");
    }
    try {
        boolean sessionValid = request.isRequestedSessionIdValid();
        // Check user's logged in otherwise an exception will be thrown
        if (sessionValid) {
            // Save any changes to the session data
            session.setAttribute("com.gtwm.pb.servlets.sessionData", sessionData);
        }
        ViewMethodsInfo viewMethods = new ViewMethods(request, this.databaseDefn);
        if (exceptionCaught != null) {
            viewMethods.setException(exceptionCaught);
        }
        context.put("view", viewMethods);
        if (sessionValid) {
            context.put("sessionData", sessionData);
        }
        context.put("viewTools", new ViewTools(request, response, this.webAppRoot));
        // If a custom user-uploaded template, add in field variables from
        // session table and report
        if (templateName != null) {
            if (templateName.startsWith("uploads/")) {
                try {
                    addCurrentDataToContext(context, sessionData, viewMethods);
                } catch (AgileBaseException abex) {
                    logger.error("Error preparing uploaded custom template variables: " + abex);
                    viewMethods.setException(abex);
                } catch (SQLException sqlex) {
                    logger.error("SQL Error preparing uploaded custom template variables: " + sqlex);
                    viewMethods.setException(sqlex);
                }
            }
        }
        AppUserInfo user = this.databaseDefn.getAuthManager().getLoggedInUser(request);
        /*
        if (user.getUsesCustomUI()) {
           String cleanCompanyName = user.getCompany().getCompanyName().toLowerCase().replaceAll("\\W", "");
           String companyPath = "gui/customisations/" + cleanCompanyName + "/";
           // Only allow templates in the company path, or the boot template
           if ((!templateName.startsWith(companyPath)) && (!templateName.equals("boot"))) {
              logger.error("Path " + templateName + " is outside of the company path " + companyPath + " for user " + user);
              templateName = null;
           }
        }
        */
    } catch (ObjectNotFoundException onfex) {
        ServletUtilMethods.logException(onfex, request, "Error getting template");
    } catch (DisallowedException dex) {
        ServletUtilMethods.logException(dex, request, "Error getting template");
    }
    templateName = "" + templateName + ".vm";
    Template template = null;
    try {
        // See note about template locations at top of file
        template = getTemplate(templateName);
    } catch (ResourceNotFoundException rnfe) {
        logger.error("Template not found: " + rnfe);
    } catch (ParseErrorException pee) {
        logger.error("Syntax error in the template: " + pee);
    }
    return template;
}

From source file:SessionSnoop.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
        count = new Integer(1);
    else/*from w w  w. jav  a 2 s  . c  o m*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);

    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");

    out.println("You've visited this page " + count + ((count == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.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>");
}