Add CookieSerializer Strategy

This allows for custom seralization of the Cookie.

Fixes gh-299
This commit is contained in:
Rob Winch
2015-11-09 10:08:51 -06:00
parent c701e1877e
commit 8c07537bec
19 changed files with 1310 additions and 80 deletions

View File

@@ -29,6 +29,8 @@ import org.springframework.session.ExpiringSession;
import org.springframework.session.SessionRepository;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDestroyedEvent;
import org.springframework.session.web.http.CookieHttpSessionStrategy;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.HttpSessionStrategy;
import org.springframework.session.web.http.SessionEventHttpSessionListenerAdapter;
import org.springframework.session.web.http.SessionRepositoryFilter;
@@ -82,10 +84,13 @@ import org.springframework.session.web.http.SessionRepositoryFilter;
@EnableScheduling
public class SpringHttpSessionConfiguration {
private HttpSessionStrategy httpSessionStrategy;
private CookieHttpSessionStrategy defaultHttpSessionStrategy = new CookieHttpSessionStrategy();
private HttpSessionStrategy httpSessionStrategy = defaultHttpSessionStrategy;
private List<HttpSessionListener> httpSessionListeners = new ArrayList<HttpSessionListener>();
@Bean
public SessionEventHttpSessionListenerAdapter sessionEventHttpSessionListenerAdapter() {
return new SessionEventHttpSessionListenerAdapter(httpSessionListeners);
@@ -95,12 +100,15 @@ public class SpringHttpSessionConfiguration {
public <S extends ExpiringSession> SessionRepositoryFilter<? extends ExpiringSession> springSessionRepositoryFilter(SessionRepository<S> sessionRepository, ServletContext servletContext) {
SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<S>(sessionRepository);
sessionRepositoryFilter.setServletContext(servletContext);
if(httpSessionStrategy != null) {
sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
}
sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
return sessionRepositoryFilter;
}
@Autowired(required = false)
public void setCookieSerializer(CookieSerializer cookieSerializer) {
this.defaultHttpSessionStrategy.setCookieSerializer(cookieSerializer);
}
@Autowired(required = false)
public void setHttpSessionStrategy(HttpSessionStrategy httpSessionStrategy) {
this.httpSessionStrategy = httpSessionStrategy;

View File

@@ -19,18 +19,19 @@ import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.springframework.session.Session;
import org.springframework.session.web.http.CookieSerializer.CookieValue;
import org.springframework.util.Assert;
/**
* A {@link HttpSessionStrategy} that uses a cookie to obtain the session from.
@@ -161,11 +162,9 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
private Pattern ALIAS_PATTERN = Pattern.compile("^[\\w-]{1,50}$");
private String cookieName = "SESSION";
private String sessionParam = DEFAULT_SESSION_ALIAS_PARAM_NAME;
private boolean isServlet3Plus = isServlet3();
private CookieSerializer cookieSerializer = new DefaultCookieSerializer();
public String getRequestedSessionId(HttpServletRequest request) {
Map<String,String> sessionIds = getSessionIds(request);
@@ -220,8 +219,9 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
Map<String,String> sessionIds = getSessionIds(request);
String sessionAlias = getCurrentSessionAlias(request);
sessionIds.put(sessionAlias, session.getId());
Cookie sessionCookie = createSessionCookie(request, sessionIds);
response.addCookie(sessionCookie);
String cookieValue = createSessionCookieValue(sessionIds);
cookieSerializer.writeCookieValue(new CookieValue(request,response,cookieValue));
}
@SuppressWarnings("unchecked")
@@ -234,26 +234,14 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
return sessionsWritten;
}
private Cookie createSessionCookie(HttpServletRequest request,
Map<String, String> sessionIds) {
Cookie sessionCookie = new Cookie(cookieName,"");
if(isServlet3Plus) {
sessionCookie.setHttpOnly(true);
}
sessionCookie.setSecure(request.isSecure());
sessionCookie.setPath(cookiePath(request));
// TODO set domain?
private String createSessionCookieValue(Map<String, String> sessionIds) {
if(sessionIds.isEmpty()) {
sessionCookie.setMaxAge(0);
return sessionCookie;
return "";
}
if(sessionIds.size() == 1) {
return sessionIds.values().iterator().next();
}
if(sessionIds.size() == 1) {
String cookieValue = sessionIds.values().iterator().next();
sessionCookie.setValue(cookieValue);
return sessionCookie;
}
StringBuffer buffer = new StringBuffer();
for(Map.Entry<String,String> entry : sessionIds.entrySet()) {
String alias = entry.getKey();
@@ -265,9 +253,7 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
buffer.append(" ");
}
buffer.deleteCharAt(buffer.length()-1);
sessionCookie.setValue(buffer.toString());
return sessionCookie;
return buffer.toString();
}
public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
@@ -275,8 +261,8 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
String requestedAlias = getCurrentSessionAlias(request);
sessionIds.remove(requestedAlias);
Cookie sessionCookie = createSessionCookie(request, sessionIds);
response.addCookie(sessionCookie);
String cookieValue = createSessionCookieValue(sessionIds);
cookieSerializer.writeCookieValue(new CookieValue(request,response,cookieValue));
}
/**
@@ -294,45 +280,30 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
}
/**
* Sets the name of the cookie to be used
* @param cookieName the name of the cookie to be used
* Sets the {@link CookieSerializer} to be used.
*
* @param cookieSerializer the cookieSerializer to set. Cannot be null.
*/
public void setCookieName(String cookieName) {
if(cookieName == null) {
throw new IllegalArgumentException("cookieName cannot be null");
}
this.cookieName = cookieName;
public void setCookieSerializer(CookieSerializer cookieSerializer) {
Assert.notNull(cookieSerializer, "cookieSerializer cannot be null");
this.cookieSerializer = cookieSerializer;
}
/**
* Retrieve the first cookie with the given name. Note that multiple
* cookies can have the same name but different paths or domains.
* @param request current servlet request
* @param name cookie name
* @return the first cookie with the given name, or {@code null} if none is found
* Sets the name of the cookie to be used
* @param cookieName the name of the cookie to be used
* @deprecated use {@link #setCookieSerializer(CookieSerializer)}
*/
private static Cookie getCookie(HttpServletRequest request, String name) {
if(request == null) {
throw new IllegalArgumentException("request cannot be null");
}
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
private static String cookiePath(HttpServletRequest request) {
return request.getContextPath() + "/";
@Deprecated
public void setCookieName(String cookieName) {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName(cookieName);
this.cookieSerializer = serializer;
}
public Map<String,String> getSessionIds(HttpServletRequest request) {
Cookie session = getCookie(request, cookieName);
String sessionCookieValue = session == null ? "" : session.getValue();
List<String> cookieValues = cookieSerializer.readCookieValues(request);
String sessionCookieValue = cookieValues.isEmpty() ? "" : cookieValues.iterator().next();
Map<String,String> result = new LinkedHashMap<String,String>();
StringTokenizer tokens = new StringTokenizer(sessionCookieValue, " ");
if(tokens.countTokens() == 1) {
@@ -411,16 +382,4 @@ public final class CookieHttpSessionStrategy implements MultiHttpSessionStrategy
throw new RuntimeException(e);
}
}
/**
* Returns true if the Servlet 3 APIs are detected.
* @return
*/
private boolean isServlet3() {
try {
ServletRequest.class.getMethod("startAsync");
return true;
} catch(NoSuchMethodException e) {}
return false;
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Strategy for reading and writing a cookie value to the
* {@link HttpServletResponse}.
*
* @author Rob Winch
* @since 1.1
*/
public interface CookieSerializer {
/**
* Writes a given {@link CookieValue} to the provided
* {@link HttpServletResponse}
*
* @param cookieValue
* the {@link CookieValue} to write to
* {@link CookieValue#getResponse()}. Cannot be null.
*/
void writeCookieValue(CookieValue cookieValue);
/**
* Reads all the matching cookies from the {@link HttpServletRequest}. The
* result is a List since there can be multiple {@link Cookie} in a single
* request with a matching name. For example, one Cookie may have a path of
* / and another of /context, but the path is not transmitted in the
* request.
*
* @param request
* the {@link HttpServletRequest} to read the cookie from. Cannot
* be null.
* @return the values of all the matching cookies
*/
List<String> readCookieValues(HttpServletRequest request);
/**
* Contains the information necessary to write a value to the
* {@link HttpServletResponse}.
*
* @author Rob Winch
* @since 1.1
*/
public class CookieValue {
private final HttpServletRequest request;
private final HttpServletResponse response;
private final String cookieValue;
/**
* Creates a new instance
*
* @param request
* the {@link HttpServletRequest} to use. Useful for
* determining the context in which the cookie is set. Cannot
* be null.
* @param response
* the {@link HttpServletResponse} to use.
* @param cookieValue
* the value of the cookie to be written. This value may be
* modified by the {@link CookieSerializer} when writing to
* the actual cookie so long as the original value is
* returned when the cookie is read.
*/
public CookieValue(HttpServletRequest request, HttpServletResponse response, String cookieValue) {
this.request = request;
this.response = response;
this.cookieValue = cookieValue;
}
/**
* Gets the request to use.
* @return the request to use. Cannot be null.
*/
public HttpServletRequest getRequest() {
return request;
}
/**
* Gets the response to write to.
* @return the response to write to. Cannot be null.
*/
public HttpServletResponse getResponse() {
return response;
}
/**
* The value to be written. This value may be modified by the {@link CookieSerializer} before written to the cookie. However, the value must be the same as the original when it is read back in.
*
* @return the value to be written
*/
public String getCookieValue() {
return cookieValue;
}
}
}

View File

@@ -0,0 +1,276 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The default implementation of {@link CookieSerializer}
*
* @author Rob Winch
* @since 1.1
*/
public class DefaultCookieSerializer implements CookieSerializer {
private String cookieName = "SESSION";
private Boolean useSecureCookie;
private boolean useHttpOnlyCookie = isServlet3();
private String cookiePath;
private int cookieMaxAge = -1;
private String domainName;
private Pattern domainNamePattern;
private String jvmRoute;
/*
* (non-Javadoc)
* @see org.springframework.session.web.http.CookieSerializer#readCookieValues(javax.servlet.http.HttpServletRequest)
*/
public List<String> readCookieValues(HttpServletRequest request) {
Cookie cookies[] = request.getCookies();
List<String> matchingCookieValues = new ArrayList<String>();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
String sessionId = cookie.getValue();
if(jvmRoute != null && sessionId.endsWith(jvmRoute)) {
sessionId = sessionId.substring(0, sessionId.length() - jvmRoute.length());
}
matchingCookieValues.add(sessionId);
}
}
}
return matchingCookieValues;
}
/*
* (non-Javadoc)
* @see
* org.springframework.session.web.http.CookieWriter#writeCookieValue(org.
* springframework.session.web.http.CookieWriter.CookieValue)
*/
public void writeCookieValue(CookieValue cookieValue) {
HttpServletRequest request = cookieValue.getRequest();
HttpServletResponse response = cookieValue.getResponse();
String requestedCookieValue = cookieValue.getCookieValue();
String actualCookieValue = jvmRoute == null ? requestedCookieValue : requestedCookieValue + jvmRoute;
Cookie sessionCookie = new Cookie(cookieName, actualCookieValue);
sessionCookie.setSecure(isSecureCookie(request));
sessionCookie.setPath(getCookiePath(request));
String domainName = getDomainName(request);
if (domainName != null) {
sessionCookie.setDomain(domainName);
}
if (useHttpOnlyCookie) {
sessionCookie.setHttpOnly(true);
}
if ("".equals(requestedCookieValue)) {
sessionCookie.setMaxAge(0);
} else {
sessionCookie.setMaxAge(cookieMaxAge);
}
response.addCookie(sessionCookie);
}
/**
* Sets if a Cookie marked as secure should be used. The default is to use
* the value of {@link HttpServletRequest#isSecure()}.
*
* @param useSecureCookie
* determines if the cookie should be marked as secure.
*/
public void setUseSecureCookie(boolean useSecureCookie) {
this.useSecureCookie = useSecureCookie;
}
/**
* Sets if a Cookie marked as HTTP Only should be used. The default is true
* in Servlet 3+ environments, else false.
*
* @param useHttpOnlyCookie
* determines if the cookie should be marked as HTTP Only.
*/
public void setUseHttpOnlyCookie(boolean useHttpOnlyCookie) {
if(useHttpOnlyCookie && !isServlet3()) {
throw new IllegalArgumentException("You cannot set useHttpOnlyCookie to true in pre Servlet 3 environment");
}
this.useHttpOnlyCookie = useHttpOnlyCookie;
}
private boolean isSecureCookie(HttpServletRequest request) {
if (useSecureCookie == null) {
return request.isSecure();
}
return useSecureCookie;
}
/**
* Sets the path of the Cookie. The default is to use the context path from
* the {@link HttpServletRequest}.
*
* @param cookiePath
* the path of the Cookie. If null, the default of the context
* path will be used.
*/
public void setCookiePath(String cookiePath) {
this.cookiePath = cookiePath;
}
public void setCookieName(String cookieName) {
if (cookieName == null) {
throw new IllegalArgumentException("cookieName cannot be null");
}
this.cookieName = cookieName;
}
/**
* Sets the maxAge property of the Cookie. The default is -1 which signals
* to delete the cookie when the browser is closed.
*
* @param cookieMaxAge
* the maxAge property of the Cookie
*/
public void setCookieMaxAge(int cookieMaxAge) {
this.cookieMaxAge = cookieMaxAge;
}
/**
* Sets an explicit Domain Name. This allow the domain of "example.com" to
* be used when the request comes from www.example.com. This allows for
* sharing the cookie across subdomains. The default is to use the current
* domain.
*
* @param domainName
* the name of the domain to use. (i.e. "example.com")
* @throws IllegalStateException if the domainNamePattern is also set
*/
public void setDomainName(String domainName) {
if (this.domainNamePattern != null) {
throw new IllegalStateException("Cannot set both domainName and domainNamePattern");
}
this.domainName = domainName;
}
/**
* <p>
* Sets a case insensitive pattern used to extract the domain name from the
* {@link HttpServletRequest#getServerName()}. The pattern should provide a
* single grouping that defines what the value is that should be matched.
* User's should be careful not to output malicious characters like new
* lines to prevent from things like
* <a href= "https://www.owasp.org/index.php/HTTP_Response_Splitting">HTTP
* Response Splitting</a>.
* </p>
*
* <p>
* If the pattern does not match, then no domain will be set. This is useful
* to ensure the domain is not set during development when localhost might
* be used.
* </p>
* <p>
* An example value might be "^.+?\\.(\\w+\\.[a-z]+)$". For the given input,
* it would provide the following explicit domain (null means no domain name
* is set):
* </p>
*
* <ul>
* <li>example.com - null</li>
* <li>child.sub.example.com - example.com</li>
* <li>localhost - null</li>
* <li>127.0.1.1 - null</li>
* </ul>
*
* @param domainNamePattern
* the case insensitive pattern to extract the domain name with
* @throws IllegalStateException if the domainName is also set
*/
public void setDomainNamePattern(String domainNamePattern) {
if (this.domainName != null) {
throw new IllegalStateException("Cannot set both domainName and domainNamePattern");
}
this.domainNamePattern = Pattern.compile(domainNamePattern, Pattern.CASE_INSENSITIVE);
}
/**
* <p>
* Used to identify which JVM to route to for session affinity. With some
* implementations (i.e. Redis) this provides no performance benefit.
* However, this can help with tracing logs of a particular user.
* </p>
* <p>
* To use set a custom route on each JVM instance and setup a frontend proxy
* to forward all requests to the JVM based on the route.
* </p>
*
* @param jvmRoute
* the JVM Route to use (i.e. "node01jvmA", "n01ja", etc)
*/
public void setJvmRoute(String jvmRoute) {
this.jvmRoute = jvmRoute;
}
private String getDomainName(HttpServletRequest request) {
if (domainName != null) {
return domainName;
}
if (domainNamePattern != null) {
Matcher matcher = domainNamePattern.matcher(request.getServerName());
if (matcher.matches()) {
return matcher.group(1);
}
}
return null;
}
private String getCookiePath(HttpServletRequest request) {
if (cookiePath == null) {
return request.getContextPath() + "/";
}
return cookiePath;
}
/**
* Returns true if the Servlet 3 APIs are detected.
*
* @return
*/
private boolean isServlet3() {
try {
ServletRequest.class.getMethod("startAsync");
return true;
} catch (NoSuchMethodException e) {
}
return false;
}
}