Java Code Examples for javax.servlet.SessionCookieConfig

The following examples show how to use javax.servlet.SessionCookieConfig. 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
Source Project: Tomcat8-Source-Read   Source File: SessionConfig.java    License: MIT License 6 votes vote down vote up
private static String getConfiguredSessionCookieName(Context context) {

        // Priority is:
        // 1. Cookie name defined in context
        // 2. Cookie name configured for app
        // 3. Default defined by spec
        if (context != null) {
            String cookieName = context.getSessionCookieName();
            if (cookieName != null && cookieName.length() > 0) {
                return cookieName;
            }

            SessionCookieConfig scc =
                context.getServletContext().getSessionCookieConfig();
            cookieName = scc.getName();
            if (cookieName != null && cookieName.length() > 0) {
                return cookieName;
            }
        }

        return null;
    }
 
Example 2
Source Project: Tomcat7.0.67   Source File: SessionConfig.java    License: Apache License 2.0 6 votes vote down vote up
private static String getConfiguredSessionCookieName(Context context) {

        // Priority is:
        // 1. Cookie name defined in context
        // 2. Cookie name configured for app
        // 3. Default defined by spec
        if (context != null) {
            String cookieName = context.getSessionCookieName();
            if (cookieName != null && cookieName.length() > 0) {
                return cookieName;
            }

            SessionCookieConfig scc =
                context.getServletContext().getSessionCookieConfig();
            cookieName = scc.getName();
            if (cookieName != null && cookieName.length() > 0) {
                return cookieName;
            }
        }

        return null;
    }
 
Example 3
Source Project: tomcatsrc   Source File: SessionConfig.java    License: Apache License 2.0 6 votes vote down vote up
private static String getConfiguredSessionCookieName(Context context) {

        // Priority is:
        // 1. Cookie name defined in context
        // 2. Cookie name configured for app
        // 3. Default defined by spec
        if (context != null) {
            String cookieName = context.getSessionCookieName();
            if (cookieName != null && cookieName.length() > 0) {
                return cookieName;
            }

            SessionCookieConfig scc =
                context.getServletContext().getSessionCookieConfig();
            cookieName = scc.getName();
            if (cookieName != null && cookieName.length() > 0) {
                return cookieName;
            }
        }

        return null;
    }
 
Example 4
Source Project: knox   Source File: GatewayServer.java    License: Apache License 2.0 6 votes vote down vote up
private WebAppContext createWebAppContext( Topology topology, File warFile, String warPath ) {
  String topoName = topology.getName();
  WebAppContext context = new WebAppContext();
  String contextPath;
  contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin( config.getGatewayPath(), topoName, warPath );
  context.setContextPath( contextPath );
  SessionCookieConfig sessionCookieConfig = context.getServletContext().getSessionCookieConfig();
  sessionCookieConfig.setName(KNOXSESSIONCOOKIENAME);
  context.setWar( warFile.getAbsolutePath() );
  context.setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName );
  context.setAttribute( "org.apache.knox.gateway.frontend.uri", getFrontendUri( context, config ) );
  context.setAttribute( GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config );
  // Add support for JSPs.
  context.setAttribute(
      "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
      ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
  context.setTempDirectory( FileUtils.getFile( warFile, "META-INF", "temp" ) );
  context.setErrorHandler( createErrorHandler() );
  context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
  ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
  context.setClassLoader(jspClassLoader);
  return context;
}
 
Example 5
Source Project: gocd   Source File: Jetty9ServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetSessionCookieConfig() throws Exception {
    when(systemEnvironment.isSessionCookieSecure()).thenReturn(true);
    jetty9Server.configure();
    jetty9Server.setSessionConfig();
    jetty9Server.startHandlers();

    WebAppContext webAppContext = (WebAppContext) getLoadedHandlers().get(WebAppContext.class);
    SessionCookieConfig sessionCookieConfig = webAppContext.getSessionHandler().getSessionCookieConfig();
    assertThat(sessionCookieConfig.isHttpOnly(), is(true));
    assertThat(sessionCookieConfig.isSecure(), is(true));
    assertThat(sessionCookieConfig.getMaxAge(), is(5678));

    when(systemEnvironment.isSessionCookieSecure()).thenReturn(false);
    jetty9Server.setSessionConfig();
    assertThat(sessionCookieConfig.isSecure(), is(false));
}
 
Example 6
Source Project: Tomcat8-Source-Read   Source File: SessionConfig.java    License: MIT License 5 votes vote down vote up
/**
 * Determine the value to use for the session cookie path for the provided
 * context.
 *
 * @param context The context
 * @return the parameter name for the session
 */
public static String getSessionCookiePath(Context context) {

    SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();

    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()) {
        // Handle special case of ROOT context where cookies require a path of
        // '/' but the servlet spec uses an empty string
        // Also ensure the cookies for a context with a path of /foo don't get
        // sent for requests with a path of /foobar
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
    } else {
        // Only handle special case of ROOT context where cookies require a
        // path of '/' but the servlet spec uses an empty string
        if (contextPath.length() == 0) {
            contextPath = "/";
        }
    }

    return contextPath;
}
 
Example 7
Source Project: Tomcat8-Source-Read   Source File: ApplicationContextFacade.java    License: MIT License 5 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (SessionCookieConfig)
            doPrivileged("getSessionCookieConfig", null);
    } else {
        return context.getSessionCookieConfig();
    }
}
 
Example 8
Source Project: Tomcat7.0.67   Source File: ApplicationContextFacade.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (SessionCookieConfig)
            doPrivileged("getSessionCookieConfig", null);
    } else {
        return context.getSessionCookieConfig();
    }
}
 
Example 9
Source Project: tomcatsrc   Source File: ApplicationContextFacade.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (SessionCookieConfig)
            doPrivileged("getSessionCookieConfig", null);
    } else {
        return context.getSessionCookieConfig();
    }
}
 
Example 10
Source Project: VulnerableJavaWebApplication   Source File: AppLauncher.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Bean
public ServletContextInitializer servletContextInitializer() {
	return new ServletContextInitializer() {
		@Override
		public void onStartup(ServletContext servletContext) throws ServletException {
			servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
			SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
			sessionCookieConfig.setHttpOnly(true);
		}
	};

}
 
Example 11
private CookieSerializer createDefaultCookieSerializer() {
	DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
	if (this.servletContext != null) {
		SessionCookieConfig sessionCookieConfig = null;
		try {
			sessionCookieConfig = this.servletContext.getSessionCookieConfig();
		}
		catch (UnsupportedOperationException ex) {
			this.logger.warn("Unable to obtain SessionCookieConfig: " + ex.getMessage());
		}
		if (sessionCookieConfig != null) {
			if (sessionCookieConfig.getName() != null) {
				cookieSerializer.setCookieName(sessionCookieConfig.getName());
			}
			if (sessionCookieConfig.getDomain() != null) {
				cookieSerializer.setDomainName(sessionCookieConfig.getDomain());
			}
			if (sessionCookieConfig.getPath() != null) {
				cookieSerializer.setCookiePath(sessionCookieConfig.getPath());
			}
			if (sessionCookieConfig.getMaxAge() != -1) {
				cookieSerializer.setCookieMaxAge(sessionCookieConfig.getMaxAge());
			}
		}
	}
	if (this.usesSpringSessionRememberMeServices) {
		cookieSerializer.setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR);
	}
	return cookieSerializer;
}
 
Example 12
Source Project: alf.io   Source File: SpringBootInitializer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
    return servletContext -> {
        WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext);
        ConfigurableEnvironment environment = ctx.getBean(ConfigurableEnvironment.class);
        SessionCookieConfig config = servletContext.getSessionCookieConfig();
        config.setHttpOnly(true);
        config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
        // force log initialization, then disable it
        XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
        XRLog.setLoggingEnabled(false);
    };
}
 
Example 13
Source Project: alf.io   Source File: Initializer.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void configureSessionCookie(ServletContext servletContext) {
    SessionCookieConfig config = servletContext.getSessionCookieConfig();

    config.setHttpOnly(true);
    
    Validate.notNull(environment, "environment cannot be null!");
    // set secure cookie only if current environment doesn't strictly need HTTP
    config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));

    // https://issues.jboss.org/browse/WFLY-3448 ?
    config.setPath(servletContext.getContextPath() + "/");
}
 
Example 14
private void copyConfig(WebConfig.SessionsConfig.CookieConfig src, SessionCookieConfig dest) {
    Optional.ofNullable(src.getComment()).ifPresent(dest::setComment);
    Optional.ofNullable(src.getDomain()).ifPresent(dest::setDomain);
    Optional.ofNullable(src.getName()).ifPresent(dest::setName);
    Optional.ofNullable(src.getPath()).ifPresent(dest::setPath);
    dest.setHttpOnly(src.isHttpOnly());
    dest.setSecure(src.isSecure());
    dest.setMaxAge(src.getMaxAge());
}
 
Example 15
Source Project: ldp4j   Source File: BootstrapUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void addSessionCookieConfigMessages(Map<String, Object> messages, SessionCookieConfig sessionCookieConfig) {
	if(sessionCookieConfig==null) {
		return;
	}
	StringBuilder builder=new StringBuilder();
	builder.append(NEW_LINE).append(VALUE_PREFIX).append("Name").append(VALUE_SEPARATOR).append(sessionCookieConfig.getName());
	builder.append(NEW_LINE).append(VALUE_PREFIX).append("Comment").append(VALUE_SEPARATOR).append(sessionCookieConfig.getComment());
	builder.append(NEW_LINE).append(VALUE_PREFIX).append("Domain").append(VALUE_SEPARATOR).append(sessionCookieConfig.getDomain());
	builder.append(NEW_LINE).append(VALUE_PREFIX).append("Path").append(VALUE_SEPARATOR).append(sessionCookieConfig.getPath());
	builder.append(NEW_LINE).append(VALUE_PREFIX).append("Max age").append(VALUE_SEPARATOR).append(sessionCookieConfig.getMaxAge());
	addMessage(messages,"Session cookie config",builder.toString());
}
 
Example 16
Source Project: gocd   Source File: Jetty9Server.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setSessionConfig() {
    SessionHandler sessionHandler = webAppContext.getSessionHandler();
    SessionCookieConfig sessionCookieConfig = sessionHandler.getSessionCookieConfig();
    sessionCookieConfig.setHttpOnly(true);
    sessionCookieConfig.setSecure(systemEnvironment.isSessionCookieSecure());
    sessionCookieConfig.setMaxAge(systemEnvironment.sessionCookieMaxAgeInSeconds());
    sessionHandler.setMaxInactiveInterval(systemEnvironment.sessionTimeoutInSeconds());
}
 
Example 17
Source Project: Tomcat8-Source-Read   Source File: ApplicationContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    return sessionCookieConfig;
}
 
Example 18
/**
 * 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);
    }

    cookie.setPath(SessionConfig.getSessionCookiePath(context));

    return cookie;
}
 
Example 19
Source Project: Tomcat8-Source-Read   Source File: JspCServletContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    return null;
}
 
Example 20
private void runValve(String jkActivation,
                      boolean validSessionId,
                      boolean expectInvokeNext,
                      boolean enableIgnore,
                      String queryString) throws Exception {
    IMocksControl control = EasyMock.createControl();
    ServletContext servletContext = control.createMock(ServletContext.class);
    Context ctx = control.createMock(Context.class);
    Request request = control.createMock(Request.class);
    Response response = control.createMock(Response.class);

    String sessionCookieName = "JSESSIONID";
    String sessionId = "cafebabe";
    String requestURI = "/test/path";
    SessionCookieConfig cookieConfig = new CookieConfig();
    cookieConfig.setDomain("example.com");
    cookieConfig.setName(sessionCookieName);
    cookieConfig.setPath("/");

    // Valve.init requires all of this stuff
    EasyMock.expect(ctx.getMBeanKeyProperties()).andStubReturn("");
    EasyMock.expect(ctx.getName()).andStubReturn("");
    EasyMock.expect(ctx.getPipeline()).andStubReturn(new StandardPipeline());
    EasyMock.expect(ctx.getDomain()).andStubReturn("foo");
    EasyMock.expect(ctx.getLogger()).andStubReturn(org.apache.juli.logging.LogFactory.getLog(LoadBalancerDrainingValve.class));
    EasyMock.expect(ctx.getServletContext()).andStubReturn(servletContext);

    // Set up the actual test
    EasyMock.expect(request.getAttribute(LoadBalancerDrainingValve.ATTRIBUTE_KEY_JK_LB_ACTIVATION)).andStubReturn(jkActivation);
    EasyMock.expect(Boolean.valueOf(request.isRequestedSessionIdValid())).andStubReturn(Boolean.valueOf(validSessionId));

    ArrayList<Cookie> cookies = new ArrayList<>();
    if(enableIgnore) {
        cookies.add(new Cookie("ignore", "true"));
    }

    if(!validSessionId) {
        MyCookie cookie = new MyCookie(cookieConfig.getName(), sessionId);
        cookie.setPath(cookieConfig.getPath());
        cookie.setValue(sessionId);

        cookies.add(cookie);

        EasyMock.expect(request.getRequestedSessionId()).andStubReturn(sessionId);
        EasyMock.expect(request.getRequestURI()).andStubReturn(requestURI);
        EasyMock.expect(request.getCookies()).andStubReturn(cookies.toArray(new Cookie[cookies.size()]));
        EasyMock.expect(request.getContext()).andStubReturn(ctx);
        EasyMock.expect(ctx.getSessionCookieName()).andStubReturn(sessionCookieName);
        EasyMock.expect(servletContext.getSessionCookieConfig()).andStubReturn(cookieConfig);
        EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
        EasyMock.expect(ctx.getSessionCookiePath()).andStubReturn("/");

        if (!enableIgnore) {
            EasyMock.expect(Boolean.valueOf(ctx.getSessionCookiePathUsesTrailingSlash())).andStubReturn(Boolean.TRUE);
            EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
            // Response will have cookie deleted
            MyCookie expectedCookie = new MyCookie(cookieConfig.getName(), "");
            expectedCookie.setPath(cookieConfig.getPath());
            expectedCookie.setMaxAge(0);

            // These two lines just mean EasyMock.expect(response.addCookie) but for a void method
            response.addCookie(expectedCookie);
            EasyMock.expect(ctx.getSessionCookieName()).andReturn(sessionCookieName); // Indirect call
            String expectedRequestURI = requestURI;
            if(null != queryString)
                expectedRequestURI = expectedRequestURI + '?' + queryString;
            response.setHeader("Location", expectedRequestURI);
            response.setStatus(307);
        }
    }

    Valve next = control.createMock(Valve.class);

    if(expectInvokeNext) {
        // Expect the "next" Valve to fire
        // Next 2 lines are basically EasyMock.expect(next.invoke(req,res)) but for a void method
        next.invoke(request, response);
        EasyMock.expectLastCall();
    }

    // Get set to actually test
    control.replay();

    LoadBalancerDrainingValve valve = new LoadBalancerDrainingValve();
    valve.setContainer(ctx);
    valve.init();
    valve.setNext(next);
    valve.setIgnoreCookieName("ignore");
    valve.setIgnoreCookieValue("true");

    valve.invoke(request, response);

    control.verify();
}
 
Example 21
Source Project: Tomcat8-Source-Read   Source File: TesterServletContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    return sessionCookieConfig;
}
 
Example 22
Source Project: spring-analysis-note   Source File: MockServletContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
	return this.sessionCookieConfig;
}
 
Example 23
Source Project: spring-analysis-note   Source File: MockServletContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
	return this.sessionCookieConfig;
}
 
Example 24
Source Project: quarkus-http   Source File: SessionCookieConfigImpl.java    License: Apache License 2.0 4 votes vote down vote up
public SessionCookieConfigImpl(final ServletContextImpl servletContext) {
    this.servletContext = servletContext;
    this.delegate = new io.undertow.server.session.SessionCookieConfig();
}
 
Example 25
Source Project: java-technology-stack   Source File: MockServletContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
	return this.sessionCookieConfig;
}
 
Example 26
Source Project: java-technology-stack   Source File: MockServletContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
	return this.sessionCookieConfig;
}
 
Example 27
Source Project: vertx-vaadin   Source File: StartupContext.java    License: MIT License 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    return null;
}
 
Example 28
Source Project: ambari-logsearch   Source File: NoServletContext.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
  return null;
}
 
Example 29
Source Project: Jinx   Source File: NettyEmbeddedContext.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SessionCookieConfig getSessionCookieConfig() {
    return null;
}
 
Example 30
Source Project: atlas   Source File: NullServletContext.java    License: Apache License 2.0 4 votes vote down vote up
public SessionCookieConfig getSessionCookieConfig() {
    return null;
}