Search in sources :

Example 26 with Cookie

use of javax.servlet.http.Cookie in project tomcat by apache.

the class ApplicationSessionCookieConfig method createSessionCookie.

/**
     * Creates a new session cookie for the given session ID
     *
     * @param context     The Context for the web application
     * @param sessionId   The ID of the session for which the cookie will be
     *                    created
     * @param secure      Should session cookie be configured as secure
     * @return the cookie for the session
     */
public static Cookie createSessionCookie(Context context, String sessionId, boolean secure) {
    SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();
    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults
    Cookie cookie = new Cookie(SessionConfig.getSessionCookieName(context), sessionId);
    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());
    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }
    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }
    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }
    String contextPath = context.getSessionCookiePath();
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = scc.getPath();
    }
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = context.getEncodedPath();
    }
    if (context.getSessionCookiePathUsesTrailingSlash()) {
        // sent for requests with a path of /foobar
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
    } else {
        // path of '/' but the servlet spec uses an empty string
        if (contextPath.length() == 0) {
            contextPath = "/";
        }
    }
    cookie.setPath(contextPath);
    return cookie;
}
Also used : Cookie(javax.servlet.http.Cookie) SessionCookieConfig(javax.servlet.SessionCookieConfig)

Example 27 with Cookie

use of javax.servlet.http.Cookie in project tomcat by apache.

the class Request method doGetSession.

// ------------------------------------------------------ Protected Methods
protected Session doGetSession(boolean create) {
    // There cannot be a session if no context has been assigned yet
    Context context = getContext();
    if (context == null) {
        return (null);
    }
    // Return the current session if it exists and is valid
    if ((session != null) && !session.isValid()) {
        session = null;
    }
    if (session != null) {
        return (session);
    }
    // Return the requested session if it exists and is valid
    Manager manager = context.getManager();
    if (manager == null) {
        // Sessions are not supported
        return (null);
    }
    if (requestedSessionId != null) {
        try {
            session = manager.findSession(requestedSessionId);
        } catch (IOException e) {
            session = null;
        }
        if ((session != null) && !session.isValid()) {
            session = null;
        }
        if (session != null) {
            session.access();
            return (session);
        }
    }
    // Create a new session if requested and the response is not committed
    if (!create) {
        return (null);
    }
    if (response != null && context.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) {
        throw new IllegalStateException(sm.getString("coyoteRequest.sessionCreateCommitted"));
    }
    // Re-use session IDs provided by the client in very limited
    // circumstances.
    String sessionId = getRequestedSessionId();
    if (requestedSessionSSL) {
    // If the session ID has been obtained from the SSL handshake then
    // use it.
    } else if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie())) {
        /* This is the common(ish) use case: using the same session ID with
             * multiple web applications on the same host. Typically this is
             * used by Portlet implementations. It only works if sessions are
             * tracked via cookies. The cookie must have a path of "/" else it
             * won't be provided for requests to all web applications.
             *
             * Any session ID provided by the client should be for a session
             * that already exists somewhere on the host. Check if the context
             * is configured for this to be confirmed.
             */
        if (context.getValidateClientProvidedNewSessionId()) {
            boolean found = false;
            for (Container container : getHost().findChildren()) {
                Manager m = ((Context) container).getManager();
                if (m != null) {
                    try {
                        if (m.findSession(sessionId) != null) {
                            found = true;
                            break;
                        }
                    } catch (IOException e) {
                    // Ignore. Problems with this manager will be
                    // handled elsewhere.
                    }
                }
            }
            if (!found) {
                sessionId = null;
            }
        }
    } else {
        sessionId = null;
    }
    session = manager.createSession(sessionId);
    // Creating a new session cookie based on that session
    if (session != null && context.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE)) {
        Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie(context, session.getIdInternal(), isSecure());
        response.addSessionCookieInternal(cookie);
    }
    if (session == null) {
        return null;
    }
    session.access();
    return session;
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) ServerCookie(org.apache.tomcat.util.http.ServerCookie) Cookie(javax.servlet.http.Cookie) Container(org.apache.catalina.Container) IOException(java.io.IOException) StringManager(org.apache.tomcat.util.res.StringManager) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager)

Example 28 with Cookie

use of javax.servlet.http.Cookie in project tomcat by apache.

the class RewriteValve method invoke.

@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    if (!getEnabled() || rules == null || rules.length == 0) {
        getNext().invoke(request, response);
        return;
    }
    if (Boolean.TRUE.equals(invoked.get())) {
        try {
            getNext().invoke(request, response);
        } finally {
            invoked.set(null);
        }
        return;
    }
    try {
        Resolver resolver = new ResolverImpl(request);
        invoked.set(Boolean.TRUE);
        // As long as MB isn't a char sequence or affiliated, this has to be
        // converted to a string
        String uriEncoding = request.getConnector().getURIEncoding();
        String originalQueryStringEncoded = request.getQueryString();
        MessageBytes urlMB = context ? request.getRequestPathMB() : request.getDecodedRequestURIMB();
        urlMB.toChars();
        CharSequence urlDecoded = urlMB.getCharChunk();
        CharSequence host = request.getServerName();
        boolean rewritten = false;
        boolean done = false;
        boolean qsa = false;
        for (int i = 0; i < rules.length; i++) {
            RewriteRule rule = rules[i];
            CharSequence test = (rule.isHost()) ? host : urlDecoded;
            CharSequence newtest = rule.evaluate(test, resolver);
            if (newtest != null && !test.equals(newtest.toString())) {
                if (containerLog.isDebugEnabled()) {
                    containerLog.debug("Rewrote " + test + " as " + newtest + " with rule pattern " + rule.getPatternString());
                }
                if (rule.isHost()) {
                    host = newtest;
                } else {
                    urlDecoded = newtest;
                }
                rewritten = true;
            }
            // Check QSA before the final reply
            if (!qsa && newtest != null && rule.isQsappend()) {
                // TODO: This logic will need some tweaks if we add QSD
                //       support
                qsa = true;
            }
            // - forbidden
            if (rule.isForbidden() && newtest != null) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                done = true;
                break;
            }
            // - gone
            if (rule.isGone() && newtest != null) {
                response.sendError(HttpServletResponse.SC_GONE);
                done = true;
                break;
            }
            // - redirect (code)
            if (rule.isRedirect() && newtest != null) {
                // Append the query string to the url if there is one and it
                // hasn't been rewritten
                String urlStringDecoded = urlDecoded.toString();
                int index = urlStringDecoded.indexOf("?");
                String rewrittenQueryStringDecoded;
                if (index == -1) {
                    rewrittenQueryStringDecoded = null;
                } else {
                    rewrittenQueryStringDecoded = urlStringDecoded.substring(index + 1);
                    urlStringDecoded = urlStringDecoded.substring(0, index);
                }
                StringBuffer urlStringEncoded = new StringBuffer(ENCODER.encode(urlStringDecoded, uriEncoding));
                if (originalQueryStringEncoded != null && originalQueryStringEncoded.length() > 0) {
                    if (rewrittenQueryStringDecoded == null) {
                        urlStringEncoded.append('?');
                        urlStringEncoded.append(originalQueryStringEncoded);
                    } else {
                        if (qsa) {
                            // if qsa is specified append the query
                            urlStringEncoded.append('?');
                            urlStringEncoded.append(ENCODER.encode(rewrittenQueryStringDecoded, uriEncoding));
                            urlStringEncoded.append('&');
                            urlStringEncoded.append(originalQueryStringEncoded);
                        } else if (index == urlStringEncoded.length() - 1) {
                            // if the ? is the last character delete it, its only purpose was to
                            // prevent the rewrite module from appending the query string
                            urlStringEncoded.deleteCharAt(index);
                        } else {
                            urlStringEncoded.append('?');
                            urlStringEncoded.append(ENCODER.encode(rewrittenQueryStringDecoded, uriEncoding));
                        }
                    }
                } else if (rewrittenQueryStringDecoded != null) {
                    urlStringEncoded.append('?');
                    urlStringEncoded.append(ENCODER.encode(rewrittenQueryStringDecoded, uriEncoding));
                }
                // 3. the url isn't absolute
                if (context && urlStringEncoded.charAt(0) == '/' && !UriUtil.hasScheme(urlStringEncoded)) {
                    urlStringEncoded.insert(0, request.getContext().getEncodedPath());
                }
                if (rule.isNoescape()) {
                    response.sendRedirect(URLDecoder.decode(urlStringEncoded.toString(), uriEncoding));
                } else {
                    response.sendRedirect(urlStringEncoded.toString());
                }
                response.setStatus(rule.getRedirectCode());
                done = true;
                break;
            }
            // - cookie
            if (rule.isCookie() && newtest != null) {
                Cookie cookie = new Cookie(rule.getCookieName(), rule.getCookieResult());
                cookie.setDomain(rule.getCookieDomain());
                cookie.setMaxAge(rule.getCookieLifetime());
                cookie.setPath(rule.getCookiePath());
                cookie.setSecure(rule.isCookieSecure());
                cookie.setHttpOnly(rule.isCookieHttpOnly());
                response.addCookie(cookie);
            }
            // - env (note: this sets a request attribute)
            if (rule.isEnv() && newtest != null) {
                for (int j = 0; j < rule.getEnvSize(); j++) {
                    request.setAttribute(rule.getEnvName(j), rule.getEnvResult(j));
                }
            }
            //   to do that)
            if (rule.isType() && newtest != null) {
                request.setContentType(rule.getTypeValue());
            }
            // - chain (skip remaining chained rules if this one does not match)
            if (rule.isChain() && newtest == null) {
                for (int j = i; j < rules.length; j++) {
                    if (!rules[j].isChain()) {
                        i = j;
                        break;
                    }
                }
                continue;
            }
            // - last (stop rewriting here)
            if (rule.isLast() && newtest != null) {
                break;
            }
            // - next (redo again)
            if (rule.isNext() && newtest != null) {
                i = 0;
                continue;
            }
            // - skip (n rules)
            if (newtest != null) {
                i += rule.getSkip();
            }
        }
        if (rewritten) {
            if (!done) {
                // See if we need to replace the query string
                String urlStringDecoded = urlDecoded.toString();
                String queryStringDecoded = null;
                int queryIndex = urlStringDecoded.indexOf('?');
                if (queryIndex != -1) {
                    queryStringDecoded = urlStringDecoded.substring(queryIndex + 1);
                    urlStringDecoded = urlStringDecoded.substring(0, queryIndex);
                }
                // Save the current context path before re-writing starts
                String contextPath = null;
                if (context) {
                    contextPath = request.getContextPath();
                }
                // Populated the encoded (i.e. undecoded) requestURI
                request.getCoyoteRequest().requestURI().setString(null);
                CharChunk chunk = request.getCoyoteRequest().requestURI().getCharChunk();
                chunk.recycle();
                if (context) {
                    // This is neither decoded nor normalized
                    chunk.append(contextPath);
                }
                chunk.append(ENCODER.encode(urlStringDecoded, uriEncoding));
                request.getCoyoteRequest().requestURI().toChars();
                // Decoded and normalized URI
                // Rewriting may have denormalized the URL
                urlStringDecoded = RequestUtil.normalize(urlStringDecoded);
                request.getCoyoteRequest().decodedURI().setString(null);
                chunk = request.getCoyoteRequest().decodedURI().getCharChunk();
                chunk.recycle();
                if (context) {
                    // This is decoded and normalized
                    chunk.append(request.getServletContext().getContextPath());
                }
                chunk.append(urlStringDecoded);
                request.getCoyoteRequest().decodedURI().toChars();
                // Set the new Query if there is one
                if (queryStringDecoded != null) {
                    request.getCoyoteRequest().queryString().setString(null);
                    chunk = request.getCoyoteRequest().queryString().getCharChunk();
                    chunk.recycle();
                    chunk.append(ENCODER.encode(queryStringDecoded, uriEncoding));
                    if (qsa && originalQueryStringEncoded != null && originalQueryStringEncoded.length() > 0) {
                        chunk.append('&');
                        chunk.append(originalQueryStringEncoded);
                    }
                    if (!chunk.isNull()) {
                        request.getCoyoteRequest().queryString().toChars();
                    }
                }
                // Set the new host if it changed
                if (!host.equals(request.getServerName())) {
                    request.getCoyoteRequest().serverName().setString(null);
                    chunk = request.getCoyoteRequest().serverName().getCharChunk();
                    chunk.recycle();
                    chunk.append(host.toString());
                    request.getCoyoteRequest().serverName().toChars();
                }
                request.getMappingData().recycle();
                // Reinvoke the whole request recursively
                try {
                    Connector connector = request.getConnector();
                    if (!connector.getProtocolHandler().getAdapter().prepare(request.getCoyoteRequest(), response.getCoyoteResponse())) {
                        return;
                    }
                    Pipeline pipeline = connector.getService().getContainer().getPipeline();
                    request.setAsyncSupported(pipeline.isAsyncSupported());
                    pipeline.getFirst().invoke(request, response);
                } catch (Exception e) {
                // This doesn't actually happen in the Catalina adapter implementation
                }
            }
        } else {
            getNext().invoke(request, response);
        }
    } finally {
        invoked.set(null);
    }
}
Also used : Cookie(javax.servlet.http.Cookie) Connector(org.apache.catalina.connector.Connector) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) ServletException(javax.servlet.ServletException) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) Pipeline(org.apache.catalina.Pipeline) CharChunk(org.apache.tomcat.util.buf.CharChunk)

Example 29 with Cookie

use of javax.servlet.http.Cookie in project cas by apereo.

the class LogoutActionTests method verifyLogoutRequestFront.

@SuppressWarnings("unchecked")
@Test
public void verifyLogoutRequestFront() throws Exception {
    final Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    this.request.setCookies(cookie);
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(StringUtils.EMPTY, null, null);
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    final LogoutProperties properties = new LogoutProperties();
    this.logoutAction = new LogoutAction(getWebApplicationServiceFactory(), this.serviceManager, properties);
    final Event event = this.logoutAction.doExecute(this.requestContext);
    assertEquals(LogoutAction.FRONT_EVENT, event.getId());
    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, logoutRequests.size());
    assertEquals(logoutRequest, logoutRequests.get(0));
}
Also used : Cookie(javax.servlet.http.Cookie) LogoutProperties(org.apereo.cas.configuration.model.core.logout.LogoutProperties) DefaultLogoutRequest(org.apereo.cas.logout.DefaultLogoutRequest) Event(org.springframework.webflow.execution.Event) LogoutRequest(org.apereo.cas.logout.LogoutRequest) DefaultLogoutRequest(org.apereo.cas.logout.DefaultLogoutRequest) Test(org.junit.Test)

Example 30 with Cookie

use of javax.servlet.http.Cookie in project cas by apereo.

the class LogoutActionTests method verifyLogoutRequestBack.

@Test
public void verifyLogoutRequestBack() throws Exception {
    final Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    this.request.setCookies(cookie);
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(StringUtils.EMPTY, null, null);
    logoutRequest.setStatus(LogoutRequestStatus.SUCCESS);
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    final LogoutProperties properties = new LogoutProperties();
    this.logoutAction = new LogoutAction(getWebApplicationServiceFactory(), this.serviceManager, properties);
    final Event event = this.logoutAction.doExecute(this.requestContext);
    assertEquals(LogoutAction.FINISH_EVENT, event.getId());
}
Also used : Cookie(javax.servlet.http.Cookie) LogoutProperties(org.apereo.cas.configuration.model.core.logout.LogoutProperties) DefaultLogoutRequest(org.apereo.cas.logout.DefaultLogoutRequest) Event(org.springframework.webflow.execution.Event) LogoutRequest(org.apereo.cas.logout.LogoutRequest) DefaultLogoutRequest(org.apereo.cas.logout.DefaultLogoutRequest) Test(org.junit.Test)

Aggregations

Cookie (javax.servlet.http.Cookie)522 Test (org.junit.Test)207 HttpServletRequest (javax.servlet.http.HttpServletRequest)84 HttpServletResponse (javax.servlet.http.HttpServletResponse)61 IOException (java.io.IOException)45 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)44 ServletException (javax.servlet.ServletException)40 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)32 HashMap (java.util.HashMap)28 HttpSession (javax.servlet.http.HttpSession)26 Locale (java.util.Locale)23 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)23 HttpCookie (java.net.HttpCookie)19 Properties (java.util.Properties)19 Date (java.util.Date)18 PrintWriter (java.io.PrintWriter)17 ArrayList (java.util.ArrayList)17 Map (java.util.Map)16 MvcResult (org.springframework.test.web.servlet.MvcResult)15 ResultMatcher (org.springframework.test.web.servlet.ResultMatcher)15