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; }
private void configureSessionCookie(SessionCookieConfig config) { Cookie cookie = this.session.getCookie(); if (cookie.getName() != null) { config.setName(cookie.getName()); } if (cookie.getDomain() != null) { config.setDomain(cookie.getDomain()); } if (cookie.getPath() != null) { config.setPath(cookie.getPath()); } if (cookie.getComment() != null) { config.setComment(cookie.getComment()); } if (cookie.getHttpOnly() != null) { config.setHttpOnly(cookie.getHttpOnly()); } if (cookie.getSecure() != null) { config.setSecure(cookie.getSecure()); } if (cookie.getMaxAge() != null) { config.setMaxAge(cookie.getMaxAge()); } }
@Test public void shouldSetSessionCookieConfig() throws Exception { when(systemEnvironment.isSessionCookieSecure()).thenReturn(true); jetty9Server.configure(); jetty9Server.setSessionConfig(); WebAppContext webAppContext = getWebAppContext(jetty9Server); SessionCookieConfig sessionCookieConfig = webAppContext.getSessionHandler().getSessionManager().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)); }
@Override public SessionCookieConfig getSessionCookieConfig() { if (SecurityUtil.isPackageProtectionEnabled()) { return (SessionCookieConfig) doPrivileged("getSessionCookieConfig", null); } else { return context.getSessionCookieConfig(); } }
/** * 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 */ 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()) { // 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 = "/"; } } cookie.setPath(contextPath); return cookie; }
/** * Configures the cookies 🍪 * * @param config cookie configuration * @param cookieName the name of the cookies * @see SessionCookieConfig#setName(String) * @see SessionCookieConfig#setMaxAge(int) */ public static void configure(SessionCookieConfig config, String cookieName) { // Change the name of the cookie config.setName(cookieName); // Change the lifetime of the cookie session: it should not be greater than the lifetime of the JWT tokens String expiration = QfsProperties.loadProperties("jwt.properties").getProperty(JwtConfig.EXPIRATION_PROPERTY); int maxAge = null != expiration ? Integer.parseInt(expiration): JwtConfig.DEFAULT_EXPIRATION; config.setMaxAge(maxAge); }
@Override public SessionCookieConfig getSessionCookieConfig() { if (!_enabled) throw new UnsupportedOperationException(); if (_sessionHandler!=null) return _sessionHandler.getSessionManager().getSessionCookieConfig(); return null; }
@Test public void customizeSessionProperties() throws Exception { Map<String, String> map = new HashMap<String, String>(); map.put("server.session.timeout", "123"); map.put("server.session.tracking-modes", "cookie,url"); map.put("server.session.cookie.name", "testname"); map.put("server.session.cookie.domain", "testdomain"); map.put("server.session.cookie.path", "/testpath"); map.put("server.session.cookie.comment", "testcomment"); map.put("server.session.cookie.http-only", "true"); map.put("server.session.cookie.secure", "true"); map.put("server.session.cookie.max-age", "60"); bindProperties(map); ConfigurableEmbeddedServletContainer factory = mock( ConfigurableEmbeddedServletContainer.class); ServletContext servletContext = mock(ServletContext.class); SessionCookieConfig sessionCookieConfig = mock(SessionCookieConfig.class); given(servletContext.getSessionCookieConfig()).willReturn(sessionCookieConfig); this.properties.customize(factory); triggerInitializers(factory, servletContext); verify(factory).setSessionTimeout(123); verify(servletContext).setSessionTrackingModes( EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)); verify(sessionCookieConfig).setName("testname"); verify(sessionCookieConfig).setDomain("testdomain"); verify(sessionCookieConfig).setPath("/testpath"); verify(sessionCookieConfig).setComment("testcomment"); verify(sessionCookieConfig).setHttpOnly(true); verify(sessionCookieConfig).setSecure(true); verify(sessionCookieConfig).setMaxAge(60); }
@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); } }; }
@Override public void contextInitialized(ServletContextEvent e) { System.setProperty(ApplicationConstants.CLIENT_DEFAULT_IMPL, ExtendedLinkedInApiClient.class.getName()); DateTimeZone.setDefault(DateTimeZone.UTC); Locale.setDefault(Locale.ENGLISH); SessionCookieConfig sessionCookieConfig = e.getServletContext().getSessionCookieConfig(); sessionCookieConfig.setHttpOnly(true); try { LogManager.getLogManager().readConfiguration(e.getServletContext().getResourceAsStream("/WEB-INF/classes/logging.properties")); } catch (IOException ex) { throw new IllegalStateException("Failed to initialize java.util.logging", ex); } ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(e.getServletContext()); Map<String, VideoExtractor> videoExtractors = ctx.getBeansOfType(VideoExtractor.class); WebUtils.videoExtractors.addAll(videoExtractors.values()); Map<String, PictureProvider> pictureProviders = ctx.getBeansOfType(PictureProvider.class); WebUtils.pictureProviders.addAll(pictureProviders.values()); Map<String, UrlShorteningService> urlShorteners = ctx.getBeansOfType(UrlShorteningService.class); WebUtils.urlShorteners.addAll(urlShorteners.values()); initializeSocialNetworks(e.getServletContext()); logger.info("Welshare startup successful"); }
@Test public void checkHttps() { ServletContext sc = mock(ServletContext.class); when(req.getServletContext()).thenReturn(sc); SessionCookieConfig scc = mock(SessionCookieConfig.class); when(sc.getSessionCookieConfig()).thenReturn(scc); applConfCtrl.checkHttpsConfiguration(req); }
@PostConstruct public void setSecureCookie() { SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig(); // servletContext is mocked in integrationTests so it will return null. if (sessionCookieConfig != null) { sessionCookieConfig.setSecure(!disableSecureCookie()); } }
private CookieSerializer createDefaultCookieSerializer() { DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); if (this.servletContext != null) { SessionCookieConfig sessionCookieConfig = null; try { sessionCookieConfig = this.servletContext.getSessionCookieConfig(); } catch (UnsupportedOperationException e) { this.logger .warn("Unable to obtain SessionCookieConfig: " + e.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; }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>"); SessionCookieConfig cookies = request.getServletContext().getSessionCookieConfig(); out.println("Found cookie: " + cookies.getName()); Cookie cookie = new Cookie("myCookieKey", "myCookieValue"); cookie.setMaxAge(60); response.addCookie(cookie); out.println("<br><br>Set a new cookie"); cookie = new Cookie("myHttpOnlyCookieKey", "myHttpOnlyCookieValue"); cookie.setHttpOnly(true); cookie.setMaxAge(60); response.addCookie(cookie); out.println("<br>Set a new HTTPOnly Cookie<br><br>"); out.println("Check what cookies are visible by"); out.println("<a href=\"http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/index-cookies.jsp\">clicking here</a>"); out.println("</body>"); out.println("</html>"); } }
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(PROFILE_HTTP)); // // FIXME and CHECKME what a mess, ouch: https://issues.jboss.org/browse/WFLY-3448 ? config.setPath(servletContext.getContextPath() + "/"); // }
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()); }
@Override public void setSessionConfig() { SessionManager sessionManager = webAppContext.getSessionHandler().getSessionManager(); SessionCookieConfig sessionCookieConfig = sessionManager.getSessionCookieConfig(); sessionCookieConfig.setHttpOnly(true); sessionCookieConfig.setSecure(systemEnvironment.isSessionCookieSecure()); sessionCookieConfig.setMaxAge(systemEnvironment.sessionCookieMaxAgeInSeconds()); sessionManager.setMaxInactiveInterval(systemEnvironment.sessionTimeoutInSeconds()); }
@Override public SessionCookieConfig getSessionCookieConfig() { return sessionCookieConfig; }
@Override public SessionCookieConfig getSessionCookieConfig() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); }
@Override public SessionCookieConfig getSessionCookieConfig() { return null; }
@Override public SessionCookieConfig getSessionCookieConfig() { // TODO Auto-generated method stub return null; }
public SessionCookieConfigImpl(final ServletContextImpl servletContext) { this.servletContext = servletContext; this.delegate = new io.undertow.server.session.SessionCookieConfig(); }