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.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 /*from www  .  j a  v a2 s . c  o m*/
 */
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.jasig.portal.spring.security.preauth.PortalPreAuthenticatedProcessingFilter.java

private void doPortalAuthentication(HttpServletRequest request) {
    // Clear out the existing session for the user if they have one
    String targetUid = null;/*  ww  w. ja v a 2 s  .c o m*/
    String originalUid = null;
    boolean swap = false;
    if (request.isRequestedSessionIdValid()) {
        try {
            HttpSession s = request.getSession(false);

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

            //No original person in session so check for swap request
            if (originalUid == null) {
                targetUid = this.identitySwapperManager.getTargetUsername(s);
                if (targetUid != null) {
                    final IPerson person = personManager.getPerson(request);
                    originalUid = person.getName();
                    swap = true;
                }
            } else {
                final IPerson person = personManager.getPerson(request);
                targetUid = person.getName();
            }

            if (s != null) {
                s.invalidate();
            }
        } catch (IllegalStateException ise) {
            // ISE indicates session was already invalidated.
            // This is fine.  This servlet trying to guarantee that the session has been invalidated;
            // it doesn't have to insist that it is the one that invalidated it.
            if (logger.isTraceEnabled()) {
                logger.trace("LoginServlet attempted to invalidate an already invalid session.", ise);
            }
        }
    }

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

    final String requestedProfile = request.getParameter(LoginController.REQUESTED_PROFILE_KEY);
    if (requestedProfile != null) {
        s.setAttribute(SessionAttributeProfileMapperImpl.DEFAULT_SESSION_ATTRIBUTE_NAME, requestedProfile);
    }

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

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

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

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

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

                person.setUserName(originalUid);
            }

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

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

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

From source file:org.kuali.coeus.sys.framework.controller.interceptor.SessionExpiredFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hrequest = (HttpServletRequest) request;
    if (hrequest.getRequestedSessionId() != null && hrequest.isRequestedSessionIdValid() == false) {
        hrequest.getSession().setAttribute(KeyConstants.SESSION_EXPIRED_IND, new Boolean(true));
    } else {/*from ww w .  j  a v  a  2 s. c  o m*/
        if (hrequest.getSession() != null) {
            hrequest.getSession().removeAttribute(KeyConstants.SESSION_EXPIRED_IND);
        }
    }

    chain.doFilter(request, response);
}

From source file:org.kuali.kra.web.filter.SessionExpiredFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hrequest = (HttpServletRequest) request;

    if (hrequest.getRequestedSessionId() != null && hrequest.isRequestedSessionIdValid() == false) {
        hrequest.getSession().setAttribute(KeyConstants.SESSION_EXPIRED_IND, new Boolean(true));
    }//ww  w.  j  a  v a  2  s.c  o  m

    chain.doFilter(request, response);
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

protected UserIdentificationInfo handleRetrieveIdentity(HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {

    UserIdentificationInfo userIdent = null;

    // go through plugins to get UserIdentity
    for (String pluginName : service.getAuthChain(httpRequest)) {
        NuxeoAuthenticationPlugin plugin = service.getPlugin(pluginName);
        if (plugin != null) {
            log.debug("Trying to retrieve userIdentification using plugin " + pluginName);
            userIdent = plugin.handleRetrieveIdentity(httpRequest, httpResponse);
            if (userIdent != null && userIdent.containsValidIdentity()) {
                // fill information for the Login module
                userIdent.setAuthPluginName(pluginName);

                // get the target login module
                String loginModulePlugin = service.getDescriptor(pluginName).getLoginModulePlugin();
                userIdent.setLoginPluginName(loginModulePlugin);

                // get the additional parameters
                Map<String, String> parameters = service.getDescriptor(pluginName).getParameters();
                if (userIdent.getLoginParameters() != null) {
                    // keep existing parameters set by the auth plugin
                    if (parameters == null) {
                        parameters = new HashMap<String, String>();
                    }/* w ww.  j a v  a 2  s. com*/
                    parameters.putAll(userIdent.getLoginParameters());
                }
                userIdent.setLoginParameters(parameters);

                break;
            }
        } else {
            log.error("Auth plugin " + pluginName + " can not be retrieved from service");
        }
    }

    // Fall back to cache (used only when avoidReautenticated=false)
    if (userIdent == null || !userIdent.containsValidIdentity()) {
        log.debug("user/password not found in request, try into identity cache");
        HttpSession session = httpRequest.getSession(false);
        if (session == null) {
            // possible we need a new session
            if (httpRequest.isRequestedSessionIdValid()) {
                session = httpRequest.getSession(true);
            }
        }
        if (session != null) {
            CachableUserIdentificationInfo savedUserInfo = retrieveIdentityFromCache(httpRequest);
            if (savedUserInfo != null) {
                log.debug("Found User identity in cache :" + savedUserInfo.getUserInfo().getUserName());
                userIdent = new UserIdentificationInfo(savedUserInfo.getUserInfo());
                savedUserInfo.setPrincipal(null);
            }
        }
    } else {
        log.debug("User/Password found as parameter of the request");
    }

    return userIdent;
}

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 ww  . j  a v a2  s .com

    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.opendatakit.odktables.util.ServiceUtils.java

@SuppressWarnings({ "rawtypes", "unused" })
public static void examineRequest(ServletContext sc, HttpServletRequest req) {
    Log logger = LogFactory.getLog(ServiceUtils.class);

    Enumeration headers = req.getHeaderNames();
    StringBuilder b = new StringBuilder();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        Enumeration fieldValues = req.getHeaders(headerName);
        while (fieldValues.hasMoreElements()) {
            String fieldValue = (String) fieldValues.nextElement();
            b.append(headerName).append(": ").append(fieldValue).append("\n");
        }/*  w w  w.  ja  v a2 s.  c  o  m*/
    }

    String contentType = req.getContentType();
    logger.info("Content type: " + contentType);

    String charEncoding = req.getCharacterEncoding();
    logger.info("Character encoding: " + charEncoding);

    String headerSet = b.toString();
    logger.info("Headers: " + headerSet);

    Cookie[] cookies = req.getCookies();
    logger.info("Cookies: " + cookies);

    String method = req.getMethod();
    logger.info("Method: " + method);

    String ctxtPath = req.getContextPath();
    logger.info("Context Path: " + ctxtPath);

    String pathInfo = req.getPathInfo();
    logger.info("Path Info: " + pathInfo);

    String query = req.getQueryString();
    logger.info("Query String: " + query);

    String ace = req.getHeader(ApiConstants.ACCEPT_CONTENT_ENCODING_HEADER);
    boolean sessionId = req.isRequestedSessionIdValid();
}

From source file:org.opendatakit.odktables.util.ServiceUtils.java

@SuppressWarnings("unused")
public static void examineRequest(ServletContext sc, HttpServletRequest req, HttpHeaders httpHeaders) {
    MultivaluedMap<String, String> headers = httpHeaders.getRequestHeaders();
    StringBuilder b = new StringBuilder();
    for (String headerName : headers.keySet()) {
        List<String> fieldValues = headers.get(headerName);
        for (String fieldValue : fieldValues) {
            b.append(headerName).append(": ").append(fieldValue).append("\n");
        }//from   w  w w .j a  v  a 2s . co m
    }
    String contentType = req.getContentType();
    String charEncoding = req.getCharacterEncoding();
    String headerSet = b.toString();
    Cookie[] cookies = req.getCookies();
    String method = req.getMethod();
    String ctxtPath = req.getContextPath();
    String pathInfo = req.getPathInfo();
    String query = req.getQueryString();
    boolean sessionId = req.isRequestedSessionIdValid();
}

From source file:org.openmrs.module.fhir.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///  w  ww.  j  a  v a2 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 (false) {
        // 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.openmrs.module.patientportaltoolkit.web.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from  www . j  a v  a2s.  co m*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // 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);
}