Example usage for javax.servlet.http HttpServletRequest getCookies

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

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:com.adito.security.DefaultLogonController.java

public SessionInfo getSessionInfo(HttpServletRequest request) {
    /**//  w  ww . j  ava 2  s.  co  m
     * LDP - This was only ever looking at the HTTP session. This causes
     * problems if the browser creates a new session but the logon ticket is
     * still valid. Look at the cookies if the ticket cannot be found.
     */

    /**
     * BPS - This is wrong and should be solved another way. 
     * getSessionInfo is *supposed* to return null if the HttpSession is 
     * not attached to a SessionInfo. This code is only partially 
     * reconfiguring the session and will prevent hasClientLoggedOn
     * from completing its job properly. This is a possible culprit for 
     * the SessionInfos hanging around as the session
     * binding listeners will not be set up correctly.
     */
    SessionInfo session = getSessionInfo(request.getSession());

    if (session == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(Constants.LOGON_TICKET)
                        || cookies[i].getName().equals(Constants.DOMAIN_LOGON_TICKET)) {
                    session = getSessionInfo(cookies[i].getValue());
                    if (session != null) {
                        log.error("----------------------------------------------------------");
                        log.error("A call has been made to getSessionInfo(HttpServletRequest)");
                        log.error("but the SessionInfo was not contained in the HttpSession");
                        log.error("However, there appears to valid cookies that DO point to a");
                        log.error("valid SessionInfo.");
                        dumpSessionStuff(session);
                        request.getSession().setAttribute(Constants.LOGON_TICKET, session.getLogonTicket());
                        request.getSession().setAttribute(Constants.SESSION_INFO, session);
                        break;
                    }
                }
            }
        }
    }

    return session;
}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }/*w w  w  . j  a  v a  2 s  .  c  o  m*/
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:com.adito.security.DefaultLogonController.java

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);//w  ww. ja va 2 s  . c  o m
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("adito.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}

From source file:com.sslexplorer.security.DefaultLogonController.java

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);/*from  w w w .ja v  a  2 s.c o m*/
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("sslexplorer.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}

From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java

/**
 * /*from  w w  w  .j a v  a  2  s.  c  o  m*/
 * This is the default root authorize method that manages the whole 
 * authorization lifecycle when accessing the backend repositories.
 * <p>
 * Based on the information included in the config file, it uses that 
 * information to manage the authorization process. If there is any URL 
 * pattern defined in the config file that matches with the url sent to 
 * the authorize() method, a new authorization class of that kind is created.
 * <p>
 * At the end, it collects the error message coming from the specific 
 * authorization class' authorize() method. If there is any problem during 
 * the processing, it's returned as well.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param id the default credential id
 * 
 * @return the HTTP error code
 * 
 * @throws HttpException
 * @throws IOException
 */
public int authorize(HttpServletRequest request, HttpServletResponse response, Cookie[] authCookies, String url,
        String id) throws HttpException, IOException, nonValidSessionException {

    logger.debug("Authorize");

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;
    boolean patternMatch = false;
    boolean rootIDExists = false;

    //UserSession
    UserSession userSession = null;

    //GSA cookie
    Cookie gsaAuthCookie = null;

    //Encoding support
    String newURL = null;

    //Try to avoid the double encoding problem
    try {
        newURL = URLDecoder.decode(url, ENCODING);
    } catch (IllegalArgumentException e) {
        logger.error("Illegal Argument when decoding/encoding URL");
        newURL = url;
    }
    URLUTF8Encoder encoder = new URLUTF8Encoder();
    url = encoder.encodeURL(new URL(newURL));

    //read vars
    if (valveConf != null) {
        //Set config vars
        setValveConf();

    } else {
        logger.error("Configuration error: Config file is not present");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Configuration error - Kerberos is not set properly");
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    //set auth Cookie                                
    Cookie[] cookies = request.getCookies();

    //SAML
    if (cookies == null) {
        cookies = authCookies;
    }

    if (cookies != null) {
        logger.debug("authCookieName is: " + authCookieName);
        for (int i = 0; i < cookies.length; i++) {
            logger.debug("Cookie found: " + cookies[i].getName() + "; value=" + cookies[i].getValue());
            if (cookies[i].getName().equals(authCookieName)) {
                gsaAuthCookie = cookies[i];
                logger.debug("Auth Cookie found!");
                break;
            }
        }
    }

    //manage Sessions                
    if (isSessionEnabled) {
        logger.debug("Session is enabled. Getting session instance");
        try {

            //Session Support. Get Sessions instance            
            sessions = Sessions.getInstance();

            //Get user session
            userSession = manageSessions(gsaAuthCookie);

        } catch (nonValidSessionException nVS) {
            //throw Exception
            throw nVS;
        } catch (Exception e) {
            logger.error("Error when geting session: " + e.getMessage(), e);
        }

    }

    //setting auth cookies
    if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies) && (!isSAML))) {
        //send auth cookies as those coming straight from the browser
        authCookies = request.getCookies();
    } else {
        //auth cookies are those that are in the session
        authCookies = userSession.getCookies();
    }

    logger.debug("Authz authorizing [" + url + "]");

    //protection
    if (repositoryConfigurations == null) {
        logger.error("Authorization Repository Vector has not been initialized");
        return HttpServletResponse.SC_UNAUTHORIZED;
    }

    //Pattern of the host that has been confiogured that needs to be macthed to the URL that is being authorized.
    RE authZHost = null;

    //The host of the GSA, need to detect a request from this host and skip past it
    RE queryHostRE = null;
    try {
        queryHostRE = new RE("/search", RE.MATCH_CASEINDEPENDENT);
    } catch (RESyntaxException reSynTaxExp) {
        logger.error("Failed to created queryHost RE: " + reSynTaxExp.getMessage());
    }

    ValveRepositoryConfiguration repository = null;

    logger.debug("Repository length: " + repositoryConfigurations.size());

    for (int i = 0; i < repositoryConfigurations.size(); i++) {

        repository = repositoryConfigurations.elementAt(i);

        logger.debug("Repository ID: " + repository.getId());

        //Pattern for this repository that needs to be macthed
        try {
            authZHost = new RE(repository.getPattern(), RE.MATCH_CASEINDEPENDENT);
        } catch (RESyntaxException reSynTaxExp) {
            logger.error("Failed to created authZHost RE: " + reSynTaxExp.getMessage());
            logger.error("Pattern trying to use: " + repository.getPattern());
        }

        if (queryHostRE.match(url)) {
            logger.debug("Query AuthZ");
            statusCode = HttpServletResponse.SC_OK;
            patternMatch = true;
        } else {
            if (authZHost.match(url)) {

                //Need the correct authZProcess implementation for this repository ID
                AuthorizationProcessImpl authZProcess = getAuthorizationProcess(repository);

                if (authZProcess != null) {
                    //URL matches a pattern
                    if (repository.getId().equals("root")) {
                        //If this is a match for the root id then it's the internal host used to test valve/test.html, so should just return valid
                        logger.debug("Internal AuthZ");
                        statusCode = HttpServletResponse.SC_OK;
                        patternMatch = true;
                        rootIDExists = true;
                    } else {
                        logger.info("Authorizing with " + repository.getId());
                        patternMatch = true;

                        //Add credentials
                        try {
                            addCredentials(authZProcess, userSession);
                        } catch (Exception e) {
                            logger.error("Error during Kerberos authZ treatment : " + e.getMessage(), e);
                        }

                        try {
                            String repoID = repository.getId();
                            statusCode = authZProcess.authorize(request, response, authCookies, url, repoID);
                            //If statusCode is UNAUTHORIZED, then the process has to stop here
                            if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                                break;
                            }
                        } catch (Exception e) {
                            logger.error("Error during authorization: " + e.getMessage(), e);
                        }
                    }
                } else {
                    logger.debug("The URL matches with the pattern defined for repository " + "["
                            + repository.getId() + "] but could not instantiate the class");
                }
            }

        }

    }
    if (!patternMatch) {
        //check if "root" repository was created in the config file
        //if not: check if the URL is a Valve one. If so, return SC_OK
        if (!rootIDExists) {
            RE internalRE = new RE(new URL(internalURL).getHost(), RE.MATCH_CASEINDEPENDENT);
            boolean samePorts = (((new URL(internalURL)).getPort()) == ((new URL(url)).getPort()));
            if ((internalRE.match(url)) && (samePorts)) {
                logger.debug("This is an internal URL");
                statusCode = HttpServletResponse.SC_OK;
            } else {
                logger.debug("No pattern has been defined at any repository for this URL");
                //Set Status Code equal to "-1", so we do know there was no pattern found
                statusCode = -1;
            }
        } else {
            logger.debug("No pattern has been defined at any repository for this URL");
            //Set Status Code equal to "-1", so we do know there was no pattern found
            statusCode = -1;
        }
    }

    //protection
    userSession = null;

    return statusCode;
}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Returns the specified Cookie object, or null if the cookie does not exist.
 * <p/>//ww w.  j  ava 2  s .  c  o  m
 * This method was derived from Atlassian <tt>CookieUtils</tt> method of
 * the same name, release under the BSD License.
 *
 * @param request the servlet request
 * @param name the name of the cookie
 * @return the Cookie object if it exists, otherwise null
 */
public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie cookies[] = request.getCookies();

    if (cookies == null || name == null || name.length() == 0) {
        return null;
    }

    //Otherwise, we have to do a linear scan for the cookie.
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
            return cookie;
        }
    }

    return null;
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from   w  w  w .j  a  va2  s. co m*/
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {
            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}

From source file:de.appsolve.padelcampus.filter.LoginFilter.java

/**
 * @param request/*from   www.j  a  v  a 2  s. c  o  m*/
 * @param response
 * @param chain
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        for (Pattern pattern : NO_FILTER_LIST) {
            if (pattern.matcher(requestURI).matches()) {
                sessionUtil.setCustomer(httpRequest, null);
                chain.doFilter(request, response);
                return;
            }
        }

        CustomerI customer = sessionUtil.getCustomer(httpRequest);
        if (customer == null) {
            String hostHeader = httpRequest.getHeader("host");
            if (!StringUtils.isEmpty(hostHeader)) {
                String[] hostHeaderSplit = hostHeader.split(":");
                customer = customerDAO.findByDomainName(hostHeaderSplit[0]);
            }
            if (customer == null) {
                String url = "";
                String serverName = httpRequest.getServerName();
                if (!StringUtils.isEmpty(serverName)) {
                    String[] domainParts = serverName.split("\\.");
                    if (domainParts.length > 2) {
                        url = httpRequest.getScheme() + "://" + domainParts[domainParts.length - 2] + "."
                                + domainParts[domainParts.length - 1];
                        if (httpRequest.getScheme().equals("http") && httpRequest.getServerPort() != 80) {
                            url += ":" + httpRequest.getServerPort();
                        }
                    }
                }
                url += PATH_START_PAGE;
                httpResponse.setStatus(HttpStatus.PERMANENT_REDIRECT.value());
                httpResponse.sendRedirect(url);
                return;
            }
            sessionUtil.setCustomer(httpRequest, customer);
        }

        //login user in case of valid login cookie
        Player user = sessionUtil.getUser(httpRequest);
        if (user == null) {
            Cookie[] cookies = httpRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName() != null && cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                        String cookieValue = cookie.getValue();
                        if (StringUtils.isEmpty(cookieValue)) {
                            loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                        } else {
                            String[] cookieValueSplit = cookieValue.split(":");
                            if (cookieValueSplit.length != 2) {
                                loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                            } else {
                                String uuid = cookieValueSplit[0];
                                String loginCookieRandomValue = cookieValueSplit[1];
                                LoginCookie loginCookie = loginUtil.isValidLoginCookie(uuid,
                                        loginCookieRandomValue);
                                if (loginCookie == null) {
                                    loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                } else {
                                    Player player = playerDAO.findByUUID(loginCookie.getPlayerUUID());
                                    if (player == null) {
                                        loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                    } else {
                                        //log user in
                                        sessionUtil.setUser(httpRequest, player);

                                        //update loginCookieHash
                                        loginUtil.updateLoginCookie(httpRequest, httpResponse);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        moduleUtil.initModules(httpRequest);
    }
    chain.doFilter(request, response);
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;//  www. ja va 2s .co m
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.paperfood.controller.Authenticate.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from ww w  .  j  av a  2 s. com
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    JSONObject resp = new JSONObject();
    MD5Hash md5;
    String status = "";
    try {
        md5 = new MD5Hash();
        String req_type = request.getParameter("type");
        if (req_type.equalsIgnoreCase("login")) //Request of Login
        {
            String loginEmail = request.getParameter("loginEmail");
            String loginPass = md5.getStringHash(request.getParameter("loginPass"));
            boolean loginRemember = request.getParameter("loginRemember").equalsIgnoreCase("true");

            DatabaseManager dm = new DatabaseManager();
            dm.open();
            PaperFoodUser user = new PaperFoodUser();
            user = (PaperFoodUser) dm.getLoggedUser(loginEmail, loginPass);
            dm.close();
            if (user != null) //Credentials are valid, create session.
            {
                session.setAttribute("paperfooduseremail", user.getEmail());
                if (loginRemember) {
                    int time = 60 * 60 * 24 * 30;
                    Cookie c = new Cookie("paperfood", user.getEmail());
                    c.setMaxAge(time);
                    response.addCookie(c);
                }
                status = "success";
            } else
                status = "invalid";
        } else if (req_type.equalsIgnoreCase("cookielogin")) //Request for Cookie-based Login.
        {
            String loginEmail = request.getParameter("loginEmail");
            session.setAttribute("paperfooduseremail", loginEmail);
            status = "success";
        } else if (req_type.equalsIgnoreCase("sessionlogin")) //Request for Session-based Login.
        {
            String useremail = (String) session.getAttribute("paperfooduseremail");
            if (useremail != null)
                status = "success";
        } else if (req_type.equalsIgnoreCase("logout")) //Request for Logout.
        {
            session.invalidate();
            Cookie[] c = request.getCookies();
            if (c != null) {
                for (int i = 0; i < c.length; i++) {
                    Cookie curr = c[i];
                    String cnm = curr.getName();
                    if (cnm.equalsIgnoreCase("paperfood")) {
                        curr.setMaxAge(0);
                        response.addCookie(curr);
                    }
                }
            }
            status = "success";
        }
    } catch (CommunicationsException e) {
        status = "unavailable";
    } catch (Exception e) {
        status = "fail";
        e.printStackTrace();
    }

    try {
        resp.put("status", status);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.println(resp);
}