Java Code Examples for javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()

The following examples show how to use javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) {
    val url = super.determineUrlToUseForThisRequest(request, response, exception);

    if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
        if (log.isDebugEnabled()) {
            log.debug("セッションがタイムアウトしました。");
        }

        return this.loginTimeoutUrl;
    }

    return url;
}
 
Example 2
private void registerSessionIfNeeded(HttpServletRequest httpRequest) {
	// rq: cette session peut-être dors et déjà invalide et c'est pourquoi on vérifie
	// isRequestedSessionIdValid
	if (httpRequest.isRequestedSessionIdValid()) {
		final HttpSession session = httpRequest.getSession(false);
		emulatedSessionListener.registerSessionIfNeeded(session);
	}
}
 
Example 3
Source Project: cxf   File: HttpServletRequestSnapshot.java    License: Apache License 2.0 5 votes vote down vote up
public HttpServletRequestSnapshot(HttpServletRequest request) {
    super(request);
    authType = request.getAuthType();
    characterEncoding = request.getCharacterEncoding();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    contextPath = request.getContextPath();
    cookies = request.getCookies();
    requestHeaderNames = request.getHeaderNames();
    Enumeration<String> tmp = request.getHeaderNames();
    while (tmp.hasMoreElements()) {
        String key = tmp.nextElement();
        headersMap.put(key, request.getHeaders(key));
    }
    localAddr = request.getLocalAddr();
    local = request.getLocale();
    localName = request.getLocalName();
    localPort = request.getLocalPort();
    method = request.getMethod();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    protocol = request.getProtocol();
    queryString = request.getQueryString();
    remoteAddr = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    remoteUser = request.getRemoteUser();
    requestURI = request.getRequestURI();
    requestURL = request.getRequestURL();
    requestedSessionId = request.getRequestedSessionId();
    schema = request.getScheme();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    servletPath = request.getServletPath();
    if (request.isRequestedSessionIdValid()) {
        session = request.getSession();
    }
    principal = request.getUserPrincipal();
}
 
Example 4
Source Project: fess   File: UserInfoHelper.java    License: Apache License 2.0 5 votes vote down vote up
public String getUserCode() {
    final HttpServletRequest request = LaRequestUtil.getRequest();

    String userCode = (String) request.getAttribute(Constants.USER_CODE);
    if (StringUtil.isNotBlank(userCode)) {
        return userCode;
    }

    userCode = getUserCodeFromRequest(request);
    if (StringUtil.isNotBlank(userCode)) {
        return userCode;
    }

    if (!request.isRequestedSessionIdValid()) {
        return null;
    }

    userCode = getUserCodeFromCookie(request);
    if (StringUtil.isBlank(userCode)) {
        userCode = getUserCodeFromUserBean(request);
        if (StringUtil.isBlank(userCode)) {
            userCode = getId();
        }
    }

    if (StringUtil.isNotBlank(userCode)) {
        updateUserSessionId(userCode);
    }
    return userCode;
}
 
Example 5
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
	String loadBalancerActivation = (String) request.getAttribute( LOAD_BALANCER_ACTIVATION_ATTRIBUTE);
	
	// First, check if the request attribute showing the activation state of the node is present
	if( loadBalancerActivation != null) {
		
		// Request attribute is present, so the node is behind a load balancer
		if( logger.isDebugEnabled()) {
			logger.debug( "Load balancer activation is " + loadBalancerActivation);
		}

		// Check, if activation state of current node is "disabled".
		if( "DIS".equals( loadBalancerActivation)) {
			
			// The node is disabled.
			try {
				HttpServletRequest req = (HttpServletRequest) request;

				// Check validity of session ID
				if( !req.isRequestedSessionIdValid()) {
					// Session ID is not valid for the current node, the requests sends a redirect to system URL specified in property "system.url"
					if( logger.isInfoEnabled()) {
						logger.info( "Requested session is invalid.");
					}
					
					HttpServletResponse resp = (HttpServletResponse) response;
					resp.sendRedirect( systemUrl);
				} else {
					
					// The session ID seems to be valid for the current node, so processing will continue.
					if( logger.isInfoEnabled()) {
						logger.info( "Requested session is valid. Proceeding with request.");
					}
					
					filterChain.doFilter( request, response);
				}
					
			} catch( ClassCastException e) {
				// We had some problem with the request. It may be no HTTP request. Processing will continue without further checks.
				logger.warn( "No HttpServletRequest?", e);
				
				filterChain.doFilter( request, response);
			}
		} else {
			// The node is either active or stopped.
			if( logger.isInfoEnabled()) {
				logger.info( "Node not disabled.");
			}

			filterChain.doFilter( request, response);
		}
	} else {
		/*
		 *  We got no information about the activation state of the current node, so we have to assume,
		 *  that the node is not behind a load balancer and is active all the time.
		 */
		
		if( logger.isInfoEnabled()) {
			logger.info( "No information about load balancer activation found.");
		}
		
		filterChain.doFilter( request, response);
	}
}
 
Example 6
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  	throws IOException, ServletException {
  	
  	logger.debug("IN");
  	
  	try {
  		
	if (request instanceof HttpServletRequest) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(false);
		boolean isValidSession = session != null;
		boolean isRequiredNewSession = false; // for those requests that require a new session anyway, 
											  // do not forward to session expired url
		String newSessionRequestAttr = httpRequest.getParameter(NEW_SESSION);
       	isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE");
       	boolean isRequestedSessionIdValid = httpRequest.isRequestedSessionIdValid();
		if (!isValidSession && !isRequestedSessionIdValid && !isRequiredNewSession) {
			// session has expired
			logger.debug("Session has expired!!");
			String sessionExpiredUrl = EnginConf.getInstance().getSessionExpiredUrl();
			if (sessionExpiredUrl == null) {
				logger.warn("Session expired URL not set!!! check engine-config.xml configuration");
			} else {
				logger.debug("Forwarding to " + sessionExpiredUrl);
				httpRequest.getRequestDispatcher(sessionExpiredUrl).forward(request, response);
				return;
			}
		}
	}
	
	chain.doFilter(request, response);
	
   } catch(Throwable t) {
   	logger.error("--------------------------------------------------------------------------------");
    logger.error("EngineCheckSessionFilter" + ":doFilter ServletException!!",t); 
	logger.error(" msg: [" + t.getMessage() + "]"); 
	Throwable z = t.getCause(); 
	if(z != null) {
		logger.error("-----------------------------");
		logger.error("ROOT CAUSE:");
		logger.error("-----------------------------"); 
		logger.error(" msg: ["+ z.getMessage() + "]"); 
		logger.error(" stacktrace:");
	}
	t.printStackTrace(); 
   	throw new ServletException(t);
} finally {
	logger.debug("OUT");
}
	
  }
 
Example 7
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  	throws IOException, ServletException {
  	
  	//logger.debug("IN");
  	
  	try {
  		
	if (request instanceof HttpServletRequest) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(false);
		boolean isValidSession = session != null;
		boolean isRequiredNewSession = false; // for those requests that require a new session anyway, 
											  // do not forward to session expired url
		String newSessionRequestAttr = httpRequest.getParameter(NEW_SESSION);
       	isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE");
       	boolean isRequestedSessionIdValid = httpRequest.isRequestedSessionIdValid();
		if (!isValidSession && !isRequestedSessionIdValid && !isRequiredNewSession) {
			// session has expired
			//logger.debug("Session has expired!!");
			String sessionExpiredUrl = getSessionExpiredUrl();
			if (sessionExpiredUrl == null || sessionExpiredUrl.trim().equals("")) {
				logger.warn("Session expired URL not set!!! check engine-config.xml configuration");
			} else {
				//logger.debug("Forwarding to " + sessionExpiredUrl);
				httpRequest.getRequestDispatcher(sessionExpiredUrl).forward(request, response);
				return;
			}
		}
	}
	
	chain.doFilter(request, response);
	
   } catch(Throwable t) {
   	logger.error("--------------------------------------------------------------------------------");
    logger.error("EngineCheckSessionFilter" + ":doFilter ServletException!!",t); 
	logger.error(" msg: [" + t.getMessage() + "]"); 
	Throwable z = t.getCause(); 
	if(z != null) {
		logger.error("-----------------------------");
		logger.error("ROOT CAUSE:");
		logger.error("-----------------------------"); 
		logger.error(" msg: ["+ z.getMessage() + "]"); 
		logger.error(" stacktrace:");
	}
	t.printStackTrace(); 
   	throw new ServletException(t);
} finally {
	//logger.debug("OUT");
}
	
  }
 
Example 8
Source Project: mycore   File: MCRServlet.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static MCRSession getSession(HttpServletRequest req) {
    boolean reusedSession = req.isRequestedSessionIdValid();
    HttpSession theSession = req.getSession(true);
    if (reusedSession) {
        LOGGER.debug(() -> "Reused HTTP session: " + theSession.getId() + ", created: " + LocalDateTime
            .ofInstant(Instant.ofEpochMilli(theSession.getCreationTime()), ZoneId.systemDefault()));
    } else {
        LOGGER.info(() -> "Created new HTTP session: " + theSession.getId());
    }
    MCRSession session = null;

    MCRSession fromHttpSession = Optional
        .ofNullable((MCRSessionResolver) theSession.getAttribute(ATTR_MYCORE_SESSION))
        .flatMap(MCRSessionResolver::resolveSession)
        .orElse(null);

    MCRSessionMgr.unlock();
    if (fromHttpSession != null && fromHttpSession.getID() != null) {
        // Take session from HttpSession with servlets
        session = fromHttpSession;

        String lastIP = session.getCurrentIP();
        String newIP = MCRFrontendUtil.getRemoteAddr(req);

        try {
            if (!MCRFrontendUtil.isIPAddrAllowed(lastIP, newIP)) {
                LOGGER.warn("Session steal attempt from IP {}, previous IP was {}. Session: {}", newIP, lastIP,
                    session);
                MCRSessionMgr.releaseCurrentSession();
                session.close(); //MCR-1409 do not leak old session
                MCRSessionMgr.unlock();//due to release above
                session = MCRSessionMgr.getCurrentSession();
                session.setCurrentIP(newIP);
            }
        } catch (UnknownHostException e) {
            throw new MCRException("Wrong transformation of IP address for this session.", e);
        }
    } else {
        // Create a new session
        session = MCRSessionMgr.getCurrentSession();
    }

    // Store current session in HttpSession
    theSession.setAttribute(ATTR_MYCORE_SESSION, new MCRSessionResolver(session));
    // store the HttpSession ID in MCRSession
    if (session.put("http.session", theSession.getId()) == null) {
        //first request
        session.beginTransaction(); //for MCRTranslation.getAvailableLanguages()
        try {
            String acceptLanguage = req.getHeader("Accept-Language");
            if (acceptLanguage != null) {
                List<Locale.LanguageRange> languageRanges = Locale.LanguageRange.parse(acceptLanguage);
                LOGGER.debug("accept languages: {}", languageRanges);
                MCRSession finalSession = session;
                Optional
                    .ofNullable(Locale.lookupTag(languageRanges, MCRTranslation.getAvailableLanguages()))
                    .ifPresent(selectedLanguage -> {
                        LOGGER.debug("selected language: {}", selectedLanguage);
                        finalSession.setCurrentLanguage(selectedLanguage);
                    });
            }
        } finally {
            if (session.transactionRequiresRollback()) {
                session.rollbackTransaction();
            }
            session.commitTransaction();
        }
    }
    // Forward MCRSessionID to XSL Stylesheets
    req.setAttribute("XSL.MCRSessionID", session.getID());

    return session;
}
 
Example 9
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
	return (httpServletRequest.getRequestedSessionId() != null) &&
               !httpServletRequest.isRequestedSessionIdValid();
}
 
Example 10
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
    return (httpServletRequest.getRequestedSessionId() != null) &&
           !httpServletRequest.isRequestedSessionIdValid();
}
 
Example 11
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
    return (httpServletRequest.getRequestedSessionId() != null) &&
           !httpServletRequest.isRequestedSessionIdValid();
}
 
Example 12
protected void processTCKReq(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request");
  PortletResponse portletResp = (PortletResponse) request.getAttribute("javax.portlet.response");
  PortletSession portletSession = portletReq.getPortletSession();
  

  PrintWriter writer = ((MimeResponse) portletResp).getWriter();

  JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails();

  /* TestCase: V2AddlEnvironmentTests_SPEC2_18_Sessions_httpSession5 */
  /* Details: "If the PortletSession object is invalidated by a */
  /* portlet, the portlet container must invalidate the associated */
  /* HttpSession object" */
  {
     String tcid = portletReq.getParameter(BUTTON_PARAM_NAME);
     if (tcid == null || !tcid.equals(V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5)) {
        
        // generate test link 
        
        PortletURL rurl = ((MimeResponse)portletResp).createRenderURL();
        rurl.setParameter(BUTTON_PARAM_NAME, V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5);
        TestLink tl = new TestLink(V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5, rurl);
        tl.writeTo(writer);
     } else {
        
        // perform test
        
        TestResult result = tcd.getTestResultFailed(V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5);
        portletSession.invalidate();
        if (!request.isRequestedSessionIdValid()) {
          result.setTcSuccess(true);
        } else {
          result.appendTcDetail("Failed because session is not invalidated.");
        }
        result.writeTo(writer);
     }
  }
  
}