use of jakarta.servlet.SessionCookieConfig in project spring-boot by spring-projects.
the class MockServletWebServer method initialize.
private void initialize() {
try {
this.servletContext = mock(ServletContext.class);
lenient().doAnswer((invocation) -> {
RegisteredServlet registeredServlet = new RegisteredServlet(invocation.getArgument(1));
MockServletWebServer.this.registeredServlets.add(registeredServlet);
return registeredServlet.getRegistration();
}).when(this.servletContext).addServlet(anyString(), any(Servlet.class));
lenient().doAnswer((invocation) -> {
RegisteredFilter registeredFilter = new RegisteredFilter(invocation.getArgument(1));
MockServletWebServer.this.registeredFilters.add(registeredFilter);
return registeredFilter.getRegistration();
}).when(this.servletContext).addFilter(anyString(), any(Filter.class));
final SessionCookieConfig sessionCookieConfig = new MockSessionCookieConfig();
given(this.servletContext.getSessionCookieConfig()).willReturn(sessionCookieConfig);
final Map<String, String> initParameters = new HashMap<>();
lenient().doAnswer((invocation) -> {
initParameters.put(invocation.getArgument(0), invocation.getArgument(1));
return null;
}).when(this.servletContext).setInitParameter(anyString(), anyString());
given(this.servletContext.getInitParameterNames()).willReturn(Collections.enumeration(initParameters.keySet()));
lenient().doAnswer((invocation) -> initParameters.get(invocation.getArgument(0))).when(this.servletContext).getInitParameter(anyString());
given(this.servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration());
for (Initializer initializer : this.initializers) {
initializer.onStartup(this.servletContext);
}
} catch (ServletException ex) {
throw new RuntimeException(ex);
}
}
use of jakarta.servlet.SessionCookieConfig 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());
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));
// Other attributes
for (Map.Entry<String, String> attribute : scc.getAttributes().entrySet()) {
switch(attribute.getKey()) {
case Constants.COOKIE_COMMENT_ATTR:
case Constants.COOKIE_DOMAIN_ATTR:
case Constants.COOKIE_MAX_AGE_ATTR:
case Constants.COOKIE_PATH_ATTR:
case Constants.COOKIE_SECURE_ATTR:
case Constants.COOKIE_HTTP_ONLY_ATTR:
// Handled above so NO-OP
break;
default:
{
cookie.setAttribute(attribute.getKey(), attribute.getValue());
}
}
}
return cookie;
}
use of jakarta.servlet.SessionCookieConfig in project tomcat by apache.
the class ContextConfig method configureContext.
private void configureContext(WebXml webxml) {
// As far as possible, process in alphabetical order so it is easy to
// check everything is present
// Some validation depends on correct public ID
context.setPublicId(webxml.getPublicId());
// Everything else in order
context.setEffectiveMajorVersion(webxml.getMajorVersion());
context.setEffectiveMinorVersion(webxml.getMinorVersion());
for (Entry<String, String> entry : webxml.getContextParams().entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
context.setDenyUncoveredHttpMethods(webxml.getDenyUncoveredHttpMethods());
context.setDisplayName(webxml.getDisplayName());
context.setDistributable(webxml.isDistributable());
for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) {
context.getNamingResources().addLocalEjb(ejbLocalRef);
}
for (ContextEjb ejbRef : webxml.getEjbRefs().values()) {
context.getNamingResources().addEjb(ejbRef);
}
for (ContextEnvironment environment : webxml.getEnvEntries().values()) {
context.getNamingResources().addEnvironment(environment);
}
for (ErrorPage errorPage : webxml.getErrorPages().values()) {
context.addErrorPage(errorPage);
}
for (FilterDef filter : webxml.getFilters().values()) {
if (filter.getAsyncSupported() == null) {
filter.setAsyncSupported("false");
}
context.addFilterDef(filter);
}
for (FilterMap filterMap : webxml.getFilterMappings()) {
context.addFilterMap(filterMap);
}
context.setJspConfigDescriptor(webxml.getJspConfigDescriptor());
for (String listener : webxml.getListeners()) {
context.addApplicationListener(listener);
}
for (Entry<String, String> entry : webxml.getLocaleEncodingMappings().entrySet()) {
context.addLocaleEncodingMappingParameter(entry.getKey(), entry.getValue());
}
// Prevents IAE
if (webxml.getLoginConfig() != null) {
context.setLoginConfig(webxml.getLoginConfig());
}
for (MessageDestinationRef mdr : webxml.getMessageDestinationRefs().values()) {
context.getNamingResources().addMessageDestinationRef(mdr);
}
// messageDestinations were ignored in Tomcat 6, so ignore here
context.setIgnoreAnnotations(webxml.isMetadataComplete());
for (Entry<String, String> entry : webxml.getMimeMappings().entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
context.setRequestCharacterEncoding(webxml.getRequestCharacterEncoding());
// Name is just used for ordering
for (ContextResourceEnvRef resource : webxml.getResourceEnvRefs().values()) {
context.getNamingResources().addResourceEnvRef(resource);
}
for (ContextResource resource : webxml.getResourceRefs().values()) {
context.getNamingResources().addResource(resource);
}
context.setResponseCharacterEncoding(webxml.getResponseCharacterEncoding());
boolean allAuthenticatedUsersIsAppRole = webxml.getSecurityRoles().contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS);
for (SecurityConstraint constraint : webxml.getSecurityConstraints()) {
if (allAuthenticatedUsersIsAppRole) {
constraint.treatAllAuthenticatedUsersAsApplicationRole();
}
context.addConstraint(constraint);
}
for (String role : webxml.getSecurityRoles()) {
context.addSecurityRole(role);
}
for (ContextService service : webxml.getServiceRefs().values()) {
context.getNamingResources().addService(service);
}
for (ServletDef servlet : webxml.getServlets().values()) {
Wrapper wrapper = context.createWrapper();
if (servlet.getLoadOnStartup() != null) {
wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue());
}
if (servlet.getEnabled() != null) {
wrapper.setEnabled(servlet.getEnabled().booleanValue());
}
wrapper.setName(servlet.getServletName());
Map<String, String> params = servlet.getParameterMap();
for (Entry<String, String> entry : params.entrySet()) {
wrapper.addInitParameter(entry.getKey(), entry.getValue());
}
wrapper.setRunAs(servlet.getRunAs());
Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs();
for (SecurityRoleRef roleRef : roleRefs) {
wrapper.addSecurityReference(roleRef.getName(), roleRef.getLink());
}
wrapper.setServletClass(servlet.getServletClass());
MultipartDef multipartdef = servlet.getMultipartDef();
if (multipartdef != null) {
long maxFileSize = -1;
long maxRequestSize = -1;
int fileSizeThreshold = 0;
if (null != multipartdef.getMaxFileSize()) {
maxFileSize = Long.parseLong(multipartdef.getMaxFileSize());
}
if (null != multipartdef.getMaxRequestSize()) {
maxRequestSize = Long.parseLong(multipartdef.getMaxRequestSize());
}
if (null != multipartdef.getFileSizeThreshold()) {
fileSizeThreshold = Integer.parseInt(multipartdef.getFileSizeThreshold());
}
wrapper.setMultipartConfigElement(new MultipartConfigElement(multipartdef.getLocation(), maxFileSize, maxRequestSize, fileSizeThreshold));
}
if (servlet.getAsyncSupported() != null) {
wrapper.setAsyncSupported(servlet.getAsyncSupported().booleanValue());
}
wrapper.setOverridable(servlet.isOverridable());
context.addChild(wrapper);
}
for (Entry<String, String> entry : webxml.getServletMappings().entrySet()) {
context.addServletMappingDecoded(entry.getKey(), entry.getValue());
}
SessionConfig sessionConfig = webxml.getSessionConfig();
if (sessionConfig != null) {
if (sessionConfig.getSessionTimeout() != null) {
context.setSessionTimeout(sessionConfig.getSessionTimeout().intValue());
}
SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();
scc.setName(sessionConfig.getCookieName());
Map<String, String> attributes = sessionConfig.getCookieAttributes();
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
scc.setAttribute(attribute.getKey(), attribute.getValue());
}
if (sessionConfig.getSessionTrackingModes().size() > 0) {
context.getServletContext().setSessionTrackingModes(sessionConfig.getSessionTrackingModes());
}
}
for (String welcomeFile : webxml.getWelcomeFiles()) {
/*
* The following will result in a welcome file of "" so don't add
* that to the context
* <welcome-file-list>
* <welcome-file/>
* </welcome-file-list>
*/
if (welcomeFile != null && welcomeFile.length() > 0) {
context.addWelcomeFile(welcomeFile);
}
}
// Do this last as it depends on servlets
for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) {
String jspServletName = context.findServletMapping("*.jsp");
if (jspServletName == null) {
jspServletName = "jsp";
}
if (context.findChild(jspServletName) != null) {
for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
context.addServletMappingDecoded(urlPattern, jspServletName, true);
}
} else {
if (log.isDebugEnabled()) {
for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
log.debug("Skipping " + urlPattern + " , no servlet " + jspServletName);
}
}
}
}
for (Entry<String, String> entry : webxml.getPostConstructMethods().entrySet()) {
context.addPostConstructMethod(entry.getKey(), entry.getValue());
}
for (Entry<String, String> entry : webxml.getPreDestroyMethods().entrySet()) {
context.addPreDestroyMethod(entry.getKey(), entry.getValue());
}
}
use of jakarta.servlet.SessionCookieConfig in project tomcat by apache.
the class SessionConfig method getSessionCookiePath.
/**
* 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()) {
// 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 = "/";
}
}
return contextPath;
}
use of jakarta.servlet.SessionCookieConfig in project tomcat by apache.
the class SessionConfig method getConfiguredSessionCookieName.
private static String getConfiguredSessionCookieName(Context context) {
// 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;
}
Aggregations