Move src to separate project to support sample
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* Copyright 2002-2014 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;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* A {@link Session} implementation that is backed by a {@link java.util.Map}. The defaults for the properties are:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>id - a secure random generated id</li>
|
||||
* <li>creationTime - the moment the {@link MapSession} was instantiated</li>
|
||||
* <li>lastAccessedTime - the moment the {@link MapSession} was instantiated</li>
|
||||
* <li>maxInactiveInterval - 30 minutes</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* This implementation has no synchronization, so it is best to use the copy constructor when working on multiple threads.
|
||||
* </p>
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public final class MapSession implements Session {
|
||||
private String id = UUID.randomUUID().toString();
|
||||
private Map<String, Object> sessionAttrs = new HashMap<String, Object>();
|
||||
private long creationTime = System.currentTimeMillis();
|
||||
private long lastAccessedTime = creationTime;
|
||||
|
||||
/**
|
||||
* Defaults to 30 minutes
|
||||
*/
|
||||
private int maxInactiveInterval = 1800;
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
*/
|
||||
public MapSession() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance from the provided {@link Session}
|
||||
*
|
||||
* @param session the {@link Session} to initialize this {@link Session} with. Cannot be null.
|
||||
*/
|
||||
public MapSession(Session session) {
|
||||
Assert.notNull(session, "session cannot be null");
|
||||
this.id = session.getId();
|
||||
this.sessionAttrs = new HashMap<String, Object>(session.getAttributeNames().size());
|
||||
for (String attrName : session.getAttributeNames()) {
|
||||
Object attrValue = session.getAttribute(attrName);
|
||||
this.sessionAttrs.put(attrName, attrValue);
|
||||
}
|
||||
this.lastAccessedTime = session.getLastAccessedTime();
|
||||
this.creationTime = session.getCreationTime();
|
||||
this.maxInactiveInterval = session.getMaxInactiveInterval();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLastAccessedTime(long lastAccessedTime) {
|
||||
this.lastAccessedTime = lastAccessedTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getLastAccessedTime() {
|
||||
return lastAccessedTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaxInactiveInterval(int interval) {
|
||||
this.maxInactiveInterval = interval;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxInactiveInterval() {
|
||||
return maxInactiveInterval;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getAttribute(String attributeName) {
|
||||
return sessionAttrs.get(attributeName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getAttributeNames() {
|
||||
return sessionAttrs.keySet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttribute(String attributeName, Object attributeValue) {
|
||||
if (attributeValue == null) {
|
||||
removeAttribute(attributeName);
|
||||
} else {
|
||||
sessionAttrs.put(attributeName, attributeValue);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAttribute(String attributeName) {
|
||||
sessionAttrs.remove(attributeName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the time that this {@link Session} was created in milliseconds since midnight of 1/1/1970 GMT. The default is when the {@link Session} was instantiated.
|
||||
* @param creationTime the time that this {@link Session} was created in milliseconds since midnight of 1/1/1970 GMT.
|
||||
*/
|
||||
public void setCreationTime(long creationTime) {
|
||||
this.creationTime = creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the identifier for this {@link Session}. The id should be a secure random generated value to prevent malicious users from guessing this value. The default is a secure random generated identifier.
|
||||
*
|
||||
* @param id the identifier for this session.
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
return obj instanceof Session && id.equals(((Session) obj).getId());
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* A {@link SessionRepository} backed by a {@link java.util.Map} and that uses a {@link MapSession}. By default a
|
||||
* {@link java.util.concurrent.ConcurrentHashMap} is used, but a custom {@link java.util.Map} can be injected to use
|
||||
* distributed maps provided by NoSQL stores like Redis and Hazelcast.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 4.0
|
||||
*/
|
||||
public class MapSessionRepository implements SessionRepository<Session> {
|
||||
private final Map<String,Session> sessions;
|
||||
|
||||
/**
|
||||
* Creates an instance backed by a {@link java.util.concurrent.ConcurrentHashMap}
|
||||
*/
|
||||
public MapSessionRepository() {
|
||||
this(new ConcurrentHashMap<String, Session>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance backed by the provided {@link java.util.Map}. This allows injecting a distributed {@link java.util.Map}.
|
||||
*
|
||||
* @param sessions the {@link java.util.Map} to use. Cannot be null.
|
||||
*/
|
||||
public MapSessionRepository(Map<String,Session> sessions) {
|
||||
Assert.notNull(sessions, "sessions cannot be null");
|
||||
this.sessions = sessions;
|
||||
}
|
||||
|
||||
public void save(Session session) {
|
||||
sessions.put(session.getId(), new MapSession(session));
|
||||
}
|
||||
|
||||
public Session getSession(String id) {
|
||||
Session result = sessions.get(id);
|
||||
return result == null ? null : new MapSession(result);
|
||||
}
|
||||
|
||||
public void delete(String id) {
|
||||
sessions.remove(id);
|
||||
}
|
||||
|
||||
public Session createSession() {
|
||||
return new MapSession();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright 2002-2014 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;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provides a way to identify a user in an agnostic way. This allows the session to be used by an HttpSession, WebSocket
|
||||
* Session, or even non web related sessions.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 4.0
|
||||
*/
|
||||
public interface Session extends Serializable {
|
||||
/**
|
||||
* Allows setting the last time this {@link Session} was accessed.
|
||||
*
|
||||
* @param lastAccessedTime the last time the client sent a request associated with the session expressed in milliseconds since midnight of 1/1/1970 GMT
|
||||
*/
|
||||
void setLastAccessedTime(long lastAccessedTime);
|
||||
|
||||
/**
|
||||
* Gets the time when this session was created in milliseconds since midnight of 1/1/1970 GMT.
|
||||
*
|
||||
* @return the time when this session was created in milliseconds since midnight of 1/1/1970 GMT.
|
||||
*/
|
||||
long getCreationTime();
|
||||
|
||||
/**
|
||||
* Gets a unique string that identifies the {@link Session}
|
||||
*
|
||||
* @return a unique string that identifies the {@link Session}
|
||||
*/
|
||||
String getId();
|
||||
|
||||
/**
|
||||
* Gets the last time this {@link Session} was accessed expressed in milliseconds since midnight of 1/1/1970 GMT
|
||||
*
|
||||
* @return the last time the client sent a request associated with the session expressed in milliseconds since midnight of 1/1/1970 GMT
|
||||
*/
|
||||
long getLastAccessedTime();
|
||||
|
||||
/**
|
||||
* Sets the maximum inactive interval in seconds between requests before this session will be invalidated. A negative time indicates that the session will never timeout.
|
||||
*
|
||||
* @param interval the number of seconds that the {@link Session} should be kept alive between client requests.
|
||||
*/
|
||||
void setMaxInactiveInterval(int interval);
|
||||
|
||||
/**
|
||||
* Gets the maximum inactive interval in seconds between requests before this session will be invalidated. A negative time indicates that the session will never timeout.
|
||||
*
|
||||
* @return the maximum inactive interval in seconds between requests before this session will be invalidated. A negative time indicates that the session will never timeout.
|
||||
*/
|
||||
int getMaxInactiveInterval();
|
||||
|
||||
/**
|
||||
* Gets the Object associated with the specified name or null if no Object is associated to that name.
|
||||
*
|
||||
* @param attributeName the name of the attribute to get
|
||||
* @return the Object associated with the specified name or null if no Object is associated to that name
|
||||
*/
|
||||
Object getAttribute(String attributeName);
|
||||
|
||||
/**
|
||||
* Gets the attribute names that have a value associated with it. Each value can be passed into {@link org.springframework.session.Session#getAttribute(String)} to obtain the attribute value.
|
||||
*
|
||||
* @return the attribute names that have a value associated with it.
|
||||
* @see #getAttribute(String)
|
||||
*/
|
||||
Set<String> getAttributeNames();
|
||||
|
||||
/**
|
||||
* Sets the attribute value for the provided attribute name. If the attributeValue is null, it has the same result as removing the attribute with {@link org.springframework.session.Session#removeAttribute(String)} .
|
||||
*
|
||||
* @param attributeName the attribute name to set
|
||||
* @param attributeValue the value of the attribute to set. If null, the attribute will be removed.
|
||||
*/
|
||||
void setAttribute(String attributeName, Object attributeValue);
|
||||
|
||||
/**
|
||||
* Removes the attribute with the provided attribute name
|
||||
* @param attributeName the name of the attribute to remove
|
||||
*/
|
||||
void removeAttribute(String attributeName);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2014 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;
|
||||
|
||||
/**
|
||||
* A repository interface for managing {@link Session} instances.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 4.0
|
||||
*/
|
||||
public interface SessionRepository<S extends Session> {
|
||||
/**
|
||||
* Ensures the {@link Session} created by {@link org.springframework.session.SessionRepository#createSession()} is saved.
|
||||
*
|
||||
* <p>
|
||||
* Some implementations may choose to save as the {@link Session} is updated by returning a {@link Session} that
|
||||
* immediately persists any changes. In this case, this method may not actually do anything.
|
||||
* </p>
|
||||
*
|
||||
* @param session the {@link Session} to save
|
||||
*/
|
||||
void save(S session);
|
||||
|
||||
/**
|
||||
* Gets the {@link Session} by the {@link Session#getId()} or null if no {@link Session} is found.
|
||||
* @param id the {@link org.springframework.session.Session#getId()} to lookup
|
||||
* @return the {@link Session} by the {@link Session#getId()} or null if no {@link Session} is found.
|
||||
*/
|
||||
S getSession(String id);
|
||||
|
||||
/**
|
||||
* Deletes the {@link Session} with the given {@link Session#getId()} or does nothing if the {@link Session} is not found.
|
||||
* @param id the {@link org.springframework.session.Session#getId()} to delete
|
||||
*/
|
||||
void delete(String id);
|
||||
|
||||
/**
|
||||
* Creates a new {@link Session} that is capable of being persisted by this {@link SessionRepository}.
|
||||
*
|
||||
* <p>This allows optimizations and customizations in how the {@link Session} is persisted. For example, the
|
||||
* implementation returned might keep track of the changes ensuring that only the delta needs to be persisted on
|
||||
* a save.</p>
|
||||
*
|
||||
* @return a new {@link Session} that is capable of being persisted by this {@link SessionRepository}
|
||||
*/
|
||||
S createSession();
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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.data.redis;
|
||||
|
||||
import org.springframework.data.redis.core.BoundHashOperations;
|
||||
import org.springframework.data.redis.core.RedisOperations;
|
||||
import org.springframework.session.MapSession;
|
||||
import org.springframework.session.Session;
|
||||
import org.springframework.session.SessionRepository;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A {@link org.springframework.session.SessionRepository} that is implemented using Spring Data's {@link org.springframework.data.redis.core.RedisOperations}. In a web environment, this is typically used in combination with
|
||||
* {@link org.springframework.session.web.SessionRepositoryFilter}.
|
||||
*
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class RedisOperationsSessionRepository implements SessionRepository<RedisOperationsSessionRepository.RedisSession> {
|
||||
private final String BOUNDED_HASH_KEY_PREFIX = "spring-security-sessions:";
|
||||
private final String CREATION_TIME_ATTR = "creationTime";
|
||||
private final String MAX_INACTIVE_ATTR = "maxInactiveInterval";
|
||||
private final String LAST_ACCESSED_ATTR = "lastAccessedTime";
|
||||
private final String SESSION_ATTR_PREFIX = "sessionAttr:";
|
||||
|
||||
|
||||
private final RedisOperations<String,Session> redisTemplate;
|
||||
|
||||
private Integer defaultMaxInactiveInterval;
|
||||
|
||||
public RedisOperationsSessionRepository(RedisOperations<String, Session> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum inactive interval in seconds between requests before newly created sessions will be
|
||||
* invalidated. A negative time indicates that the session will never timeout.
|
||||
*
|
||||
* @param defaultMaxInactiveInterval the number of seconds that the {@link Session} should be kept alive between client requests.
|
||||
*/
|
||||
public void setDefaultMaxInactiveInterval(int defaultMaxInactiveInterval) {
|
||||
this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(RedisSession session) {
|
||||
session.saveDelta();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisSession getSession(String id) {
|
||||
Map<Object, Object> entries = getOperations(id).entries();
|
||||
if(entries.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
MapSession loaded = new MapSession();
|
||||
loaded.setId(id);
|
||||
for(Map.Entry<Object,Object> entry : entries.entrySet()) {
|
||||
String key = (String) entry.getKey();
|
||||
if(CREATION_TIME_ATTR.equals(key)) {
|
||||
loaded.setCreationTime((Long) entry.getValue());
|
||||
} else if(MAX_INACTIVE_ATTR.equals(key)) {
|
||||
loaded.setMaxInactiveInterval((Integer) entry.getValue());
|
||||
} else if(LAST_ACCESSED_ATTR.equals(key)) {
|
||||
loaded.setLastAccessedTime((Long) entry.getValue());
|
||||
} else if(key.startsWith(SESSION_ATTR_PREFIX)) {
|
||||
loaded.setAttribute(key.substring(SESSION_ATTR_PREFIX.length()), entry.getValue());
|
||||
}
|
||||
}
|
||||
return new RedisSession(loaded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String sessionId) {
|
||||
String key = getKey(sessionId);
|
||||
this.redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisSession createSession() {
|
||||
RedisSession redisSession = new RedisSession();
|
||||
if(defaultMaxInactiveInterval != null) {
|
||||
redisSession.setMaxInactiveInterval(defaultMaxInactiveInterval);
|
||||
}
|
||||
return redisSession;
|
||||
}
|
||||
|
||||
private String getKey(String sessionId) {
|
||||
return BOUNDED_HASH_KEY_PREFIX + sessionId;
|
||||
}
|
||||
|
||||
private BoundHashOperations<String, Object, Object> getOperations(String sessionId) {
|
||||
String key = getKey(sessionId);
|
||||
return this.redisTemplate.boundHashOps(key);
|
||||
}
|
||||
|
||||
class RedisSession implements Session {
|
||||
private final MapSession cached;
|
||||
private Map<String, Object> delta = new HashMap<String,Object>();
|
||||
|
||||
private RedisSession() {
|
||||
this(new MapSession());
|
||||
delta.put(CREATION_TIME_ATTR, getCreationTime());
|
||||
delta.put(MAX_INACTIVE_ATTR, getMaxInactiveInterval());
|
||||
delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime());
|
||||
}
|
||||
|
||||
private RedisSession(MapSession cached) {
|
||||
this.cached = cached;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLastAccessedTime(long lastAccessedTime) {
|
||||
cached.setLastAccessedTime(lastAccessedTime);
|
||||
delta.put(LAST_ACCESSED_ATTR, getLastAccessedTime());
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreationTime() {
|
||||
return cached.getCreationTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return cached.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getLastAccessedTime() {
|
||||
return cached.getLastAccessedTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaxInactiveInterval(int interval) {
|
||||
cached.setMaxInactiveInterval(interval);
|
||||
delta.put(MAX_INACTIVE_ATTR, getMaxInactiveInterval());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxInactiveInterval() {
|
||||
return cached.getMaxInactiveInterval();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getAttribute(String attributeName) {
|
||||
return cached.getAttribute(attributeName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getAttributeNames() {
|
||||
return cached.getAttributeNames();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttribute(String attributeName, Object attributeValue) {
|
||||
cached.setAttribute(attributeName, attributeValue);
|
||||
delta.put(SESSION_ATTR_PREFIX + attributeName, attributeValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAttribute(String attributeName) {
|
||||
cached.removeAttribute(attributeName);
|
||||
delta.put(SESSION_ATTR_PREFIX + attributeName, null);
|
||||
}
|
||||
|
||||
private void saveDelta() {
|
||||
getOperations(getId()).putAll(delta);
|
||||
getOperations(getId()).expire(getMaxInactiveInterval(), TimeUnit.SECONDS);
|
||||
delta.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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;
|
||||
|
||||
import org.springframework.session.Session;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* A {@link HttpSessionStrategy} that uses a cookie to obtain the session from. Specifically, this implementation will
|
||||
* allow specifying a cookie name using {@link CookieHttpSessionStrategy#setCookieName(String)}. The default is "SESSION".
|
||||
*
|
||||
* When a session is created, the HTTP response will have a cookie with the specified cookie name and the value of the
|
||||
* session id. The cookie will be marked as a session cookie, marked as HTTPOnly, and if
|
||||
* {@link javax.servlet.http.HttpServletRequest#isSecure()} returns true, the cookie will be marked as secure. For example:
|
||||
*
|
||||
* <pre>
|
||||
* HTTP/1.1 200 OK
|
||||
* Set-Cookie: SESSION=f81d4fae-7dec-11d0-a765-00a0c91e6bf6; Secure; HttpOnly
|
||||
* </pre>
|
||||
*
|
||||
* The client should now include the session in each request by specifying the same cookie in their request. For example:
|
||||
*
|
||||
* <pre>
|
||||
* GET /messages/ HTTP/1.1
|
||||
* Host: example.com
|
||||
* Cookie: SESSION=f81d4fae-7dec-11d0-a765-00a0c91e6bf6
|
||||
* </pre>
|
||||
*
|
||||
* When the session is invalidated, the server will send an HTTP response that expires the cookie. For example:
|
||||
*
|
||||
* <pre>
|
||||
* HTTP/1.1 200 OK
|
||||
* Set-Cookie: SESSION=f81d4fae-7dec-11d0-a765-00a0c91e6bf6; Expires=Thur, 1 Jan 1970 00:00:00 GMT; Secure; HttpOnly
|
||||
* </pre>
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public final class CookieHttpSessionStrategy implements HttpSessionStrategy {
|
||||
private String cookieName = "SESSION";
|
||||
|
||||
@Override
|
||||
public String getRequestedSessionId(HttpServletRequest request) {
|
||||
Cookie session = getCookie(request, cookieName);
|
||||
return session == null ? null : session.getValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
|
||||
Cookie cookie = new Cookie(cookieName, session.getId());
|
||||
cookie.setHttpOnly(true);
|
||||
cookie.setSecure(request.isSecure());
|
||||
cookie.setPath(cookiePath(request));
|
||||
response.addCookie(cookie);
|
||||
|
||||
// TODO set the domain?
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
|
||||
Cookie sessionCookie = new Cookie(cookieName,"");
|
||||
sessionCookie.setMaxAge(0);
|
||||
sessionCookie.setHttpOnly(true);
|
||||
sessionCookie.setSecure(request.isSecure());
|
||||
sessionCookie.setPath(cookiePath(request));
|
||||
response.addCookie(sessionCookie);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the name of the cookie to be used
|
||||
* @param cookieName
|
||||
*/
|
||||
public void setCookieName(String cookieName) {
|
||||
Assert.notNull(cookieName, "cookieName cannot be null");
|
||||
this.cookieName = cookieName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
private static Cookie getCookie(HttpServletRequest request, String name) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Cookie cookies[] = request.getCookies();
|
||||
Cookie result = null;
|
||||
if (cookies != null) {
|
||||
for (Cookie cookie : cookies) {
|
||||
if (name.equals(cookie.getName())) {
|
||||
if(cookiePath(request).equals(cookie.getPath())) {
|
||||
return cookie;
|
||||
}
|
||||
result = cookie;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String cookiePath(HttpServletRequest request) {
|
||||
return request.getContextPath() + "/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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;
|
||||
|
||||
import org.springframework.session.Session;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* A {@link HttpSessionStrategy} that uses a header to obtain the session from. Specifically, this implementation will
|
||||
* allow specifying a header name using {@link HeaderHttpSessionStrategy#setHeaderName(String)}. The default is "x-auth-token".
|
||||
*
|
||||
* When a session is created, the HTTP response will have a response header of the specified name and the value of the session id. For example:
|
||||
*
|
||||
* <pre>
|
||||
* HTTP/1.1 200 OK
|
||||
* x-auth-token: f81d4fae-7dec-11d0-a765-00a0c91e6bf6
|
||||
* </pre>
|
||||
*
|
||||
* The client should now include the session in each request by specifying the same header in their request. For example:
|
||||
*
|
||||
* <pre>
|
||||
* GET /messages/ HTTP/1.1
|
||||
* Host: example.com
|
||||
* x-auth-token: f81d4fae-7dec-11d0-a765-00a0c91e6bf6
|
||||
* </pre>
|
||||
*
|
||||
* When the session is invalidated, the server will send an HTTP response that has the header name and a blank value. For example:
|
||||
*
|
||||
* <pre>
|
||||
* HTTP/1.1 200 OK
|
||||
* x-auth-token:
|
||||
* </pre>
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class HeaderHttpSessionStrategy implements HttpSessionStrategy {
|
||||
private String headerName = "x-auth-token";
|
||||
|
||||
@Override
|
||||
public String getRequestedSessionId(HttpServletRequest request) {
|
||||
return request.getHeader(headerName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
|
||||
response.addHeader(headerName, session.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
|
||||
response.addHeader(headerName, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of the header to obtain the session id from. Default is "x-auth-token".
|
||||
*
|
||||
* @param headerName the name of the header to obtain the session id from.
|
||||
*/
|
||||
public void setHeaderName(String headerName) {
|
||||
Assert.notNull(headerName, "headerName cannot be null");
|
||||
this.headerName = headerName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2002-2014 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;
|
||||
|
||||
import org.springframework.session.Session;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* A strategy for mapping HTTP request and responses to a {@link Session}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public interface HttpSessionStrategy {
|
||||
|
||||
/**
|
||||
* Obtains the requested session id from the provided {@link javax.servlet.http.HttpServletRequest}. For example,
|
||||
* the session id might come from a cookie or a request header.
|
||||
*
|
||||
* @param request the {@link javax.servlet.http.HttpServletRequest} to obtain the session id from. Cannot be null.
|
||||
* @return the {@link javax.servlet.http.HttpServletRequest} to obtain the session id from.
|
||||
*/
|
||||
String getRequestedSessionId(HttpServletRequest request);
|
||||
|
||||
/**
|
||||
* This method is invoked when a new session is created and should inform a client what the new session id is. For
|
||||
* example, it might create a new cookie with the session id in it or set an HTTP response header with the value of
|
||||
* the new session id.
|
||||
*
|
||||
* Some implementations may wish to associate additional information to the {@link Session} at this time. For example, they
|
||||
* may wish to add the IP Address, browser headers, the username, etc to the {@link org.springframework.session.Session}.
|
||||
*
|
||||
* @param session the {@link org.springframework.session.Session} that is being sent to the client. Cannot be null.
|
||||
* @param request the {@link javax.servlet.http.HttpServletRequest} that create the new {@link org.springframework.session.Session} Cannot be null.
|
||||
* @param response the {@link javax.servlet.http.HttpServletResponse} that is associated with the {@link javax.servlet.http.HttpServletRequest} that created the new {@link org.springframework.session.Session} Cannot be null.
|
||||
*/
|
||||
void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response);
|
||||
|
||||
/**
|
||||
* This method is invoked when a session is invalidated and should inform a client that the session id is no longer valid. For
|
||||
* example, it might remove a cookie with the session id in it or set an HTTP response header with an empty value indicating
|
||||
* to the client to no longer submit that session id.
|
||||
*
|
||||
* @param request the {@link javax.servlet.http.HttpServletRequest} that invalidated the {@link org.springframework.session.Session} Cannot be null.
|
||||
* @param response the {@link javax.servlet.http.HttpServletResponse} that is associated with the {@link javax.servlet.http.HttpServletRequest} that invalidated the {@link org.springframework.session.Session} Cannot be null.
|
||||
*/
|
||||
void onInvalidateSession(HttpServletRequest request, HttpServletResponse response);
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
/*
|
||||
* Copyright 2002-2012 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;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Base class for response wrappers which encapsulate the logic for handling an event when the
|
||||
* {@link javax.servlet.http.HttpServletResponse} is committed.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper {
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private boolean disableOnCommitted;
|
||||
|
||||
/**
|
||||
* @param response the response to be wrapped
|
||||
*/
|
||||
public OnCommittedResponseWrapper(HttpServletResponse response) {
|
||||
super(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke this method to disable invoking {@link OnCommittedResponseWrapper#onResponseCommitted()} when the {@link javax.servlet.http.HttpServletResponse} is
|
||||
* committed. This can be useful in the event that Async Web Requests are
|
||||
* made.
|
||||
*/
|
||||
public void disableOnResponseCommitted() {
|
||||
this.disableOnCommitted = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implement the logic for handling the {@link javax.servlet.http.HttpServletResponse} being committed
|
||||
*/
|
||||
protected abstract void onResponseCommitted();
|
||||
|
||||
/**
|
||||
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the
|
||||
* superclass <code>sendError()</code>
|
||||
*/
|
||||
@Override
|
||||
public final void sendError(int sc) throws IOException {
|
||||
doOnResponseCommitted();
|
||||
super.sendError(sc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the
|
||||
* superclass <code>sendError()</code>
|
||||
*/
|
||||
@Override
|
||||
public final void sendError(int sc, String msg) throws IOException {
|
||||
doOnResponseCommitted();
|
||||
super.sendError(sc, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the
|
||||
* superclass <code>sendRedirect()</code>
|
||||
*/
|
||||
@Override
|
||||
public final void sendRedirect(String location) throws IOException {
|
||||
doOnResponseCommitted();
|
||||
super.sendRedirect(location);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the calling
|
||||
* <code>getOutputStream().close()</code> or <code>getOutputStream().flush()</code>
|
||||
*/
|
||||
@Override
|
||||
public ServletOutputStream getOutputStream() throws IOException {
|
||||
return new SaveContextServletOutputStream(super.getOutputStream());
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the
|
||||
* <code>getWriter().close()</code> or <code>getWriter().flush()</code>
|
||||
*/
|
||||
@Override
|
||||
public PrintWriter getWriter() throws IOException {
|
||||
return new SaveContextPrintWriter(super.getWriter());
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the
|
||||
* superclass <code>flushBuffer()</code>
|
||||
*/
|
||||
@Override
|
||||
public void flushBuffer() throws IOException {
|
||||
doOnResponseCommitted();
|
||||
super.flushBuffer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls <code>onResponseCommmitted()</code> with the current contents as long as
|
||||
* {@link #disableOnResponseCommitted()()} was not invoked.
|
||||
*/
|
||||
private void doOnResponseCommitted() {
|
||||
if(!disableOnCommitted) {
|
||||
onResponseCommitted();
|
||||
} else if(logger.isDebugEnabled()){
|
||||
logger.debug("Skip invoking on");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures {@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling the prior to methods that commit the response. We delegate all methods
|
||||
* to the original {@link java.io.PrintWriter} to ensure that the behavior is as close to the original {@link java.io.PrintWriter}
|
||||
* as possible. See SEC-2039
|
||||
* @author Rob Winch
|
||||
*/
|
||||
private class SaveContextPrintWriter extends PrintWriter {
|
||||
private final PrintWriter delegate;
|
||||
|
||||
public SaveContextPrintWriter(PrintWriter delegate) {
|
||||
super(delegate);
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
doOnResponseCommitted();
|
||||
delegate.flush();
|
||||
}
|
||||
|
||||
public void close() {
|
||||
doOnResponseCommitted();
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return delegate.hashCode();
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
return delegate.equals(obj);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return getClass().getName() + "[delegate=" + delegate.toString() + "]";
|
||||
}
|
||||
|
||||
public boolean checkError() {
|
||||
return delegate.checkError();
|
||||
}
|
||||
|
||||
public void write(int c) {
|
||||
delegate.write(c);
|
||||
}
|
||||
|
||||
public void write(char[] buf, int off, int len) {
|
||||
delegate.write(buf, off, len);
|
||||
}
|
||||
|
||||
public void write(char[] buf) {
|
||||
delegate.write(buf);
|
||||
}
|
||||
|
||||
public void write(String s, int off, int len) {
|
||||
delegate.write(s, off, len);
|
||||
}
|
||||
|
||||
public void write(String s) {
|
||||
delegate.write(s);
|
||||
}
|
||||
|
||||
public void print(boolean b) {
|
||||
delegate.print(b);
|
||||
}
|
||||
|
||||
public void print(char c) {
|
||||
delegate.print(c);
|
||||
}
|
||||
|
||||
public void print(int i) {
|
||||
delegate.print(i);
|
||||
}
|
||||
|
||||
public void print(long l) {
|
||||
delegate.print(l);
|
||||
}
|
||||
|
||||
public void print(float f) {
|
||||
delegate.print(f);
|
||||
}
|
||||
|
||||
public void print(double d) {
|
||||
delegate.print(d);
|
||||
}
|
||||
|
||||
public void print(char[] s) {
|
||||
delegate.print(s);
|
||||
}
|
||||
|
||||
public void print(String s) {
|
||||
delegate.print(s);
|
||||
}
|
||||
|
||||
public void print(Object obj) {
|
||||
delegate.print(obj);
|
||||
}
|
||||
|
||||
public void println() {
|
||||
delegate.println();
|
||||
}
|
||||
|
||||
public void println(boolean x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(char x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(int x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(long x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(float x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(double x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(char[] x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(String x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public void println(Object x) {
|
||||
delegate.println(x);
|
||||
}
|
||||
|
||||
public PrintWriter printf(String format, Object... args) {
|
||||
return delegate.printf(format, args);
|
||||
}
|
||||
|
||||
public PrintWriter printf(Locale l, String format, Object... args) {
|
||||
return delegate.printf(l, format, args);
|
||||
}
|
||||
|
||||
public PrintWriter format(String format, Object... args) {
|
||||
return delegate.format(format, args);
|
||||
}
|
||||
|
||||
public PrintWriter format(Locale l, String format, Object... args) {
|
||||
return delegate.format(l, format, args);
|
||||
}
|
||||
|
||||
public PrintWriter append(CharSequence csq) {
|
||||
return delegate.append(csq);
|
||||
}
|
||||
|
||||
public PrintWriter append(CharSequence csq, int start, int end) {
|
||||
return delegate.append(csq, start, end);
|
||||
}
|
||||
|
||||
public PrintWriter append(char c) {
|
||||
return delegate.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures{@link OnCommittedResponseWrapper#onResponseCommitted()} is invoked before calling methods that commit the response. We delegate all methods
|
||||
* to the original {@link javax.servlet.ServletOutputStream} to ensure that the behavior is as close to the original {@link javax.servlet.ServletOutputStream}
|
||||
* as possible. See SEC-2039
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
private class SaveContextServletOutputStream extends ServletOutputStream {
|
||||
private final ServletOutputStream delegate;
|
||||
|
||||
public SaveContextServletOutputStream(ServletOutputStream delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
public void write(int b) throws IOException {
|
||||
this.delegate.write(b);
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
doOnResponseCommitted();
|
||||
delegate.flush();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
doOnResponseCommitted();
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return delegate.hashCode();
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
return delegate.equals(obj);
|
||||
}
|
||||
|
||||
public void print(boolean b) throws IOException {
|
||||
delegate.print(b);
|
||||
}
|
||||
|
||||
public void print(char c) throws IOException {
|
||||
delegate.print(c);
|
||||
}
|
||||
|
||||
public void print(double d) throws IOException {
|
||||
delegate.print(d);
|
||||
}
|
||||
|
||||
public void print(float f) throws IOException {
|
||||
delegate.print(f);
|
||||
}
|
||||
|
||||
public void print(int i) throws IOException {
|
||||
delegate.print(i);
|
||||
}
|
||||
|
||||
public void print(long l) throws IOException {
|
||||
delegate.print(l);
|
||||
}
|
||||
|
||||
public void print(String arg0) throws IOException {
|
||||
delegate.print(arg0);
|
||||
}
|
||||
|
||||
public void println() throws IOException {
|
||||
delegate.println();
|
||||
}
|
||||
|
||||
public void println(boolean b) throws IOException {
|
||||
delegate.println(b);
|
||||
}
|
||||
|
||||
public void println(char c) throws IOException {
|
||||
delegate.println(c);
|
||||
}
|
||||
|
||||
public void println(double d) throws IOException {
|
||||
delegate.println(d);
|
||||
}
|
||||
|
||||
public void println(float f) throws IOException {
|
||||
delegate.println(f);
|
||||
}
|
||||
|
||||
public void println(int i) throws IOException {
|
||||
delegate.println(i);
|
||||
}
|
||||
|
||||
public void println(long l) throws IOException {
|
||||
delegate.println(l);
|
||||
}
|
||||
|
||||
public void println(String s) throws IOException {
|
||||
delegate.println(s);
|
||||
}
|
||||
|
||||
public void write(byte[] b) throws IOException {
|
||||
delegate.write(b);
|
||||
}
|
||||
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
delegate.write(b, off, len);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return getClass().getName() + "[delegate=" + delegate.toString() + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Allows for easily ensuring that a request is only invoked once per request. This is a simplified version of spring-web's
|
||||
* OncePerRequestFilter and copied to reduce the foot print required to use the session support.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
abstract class OncePerRequestFilter implements Filter {
|
||||
/**
|
||||
* Suffix that gets appended to the filter name for the
|
||||
* "already filtered" request attribute.
|
||||
*/
|
||||
public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED";
|
||||
|
||||
private String alreadyFilteredAttributeName = getClass().getName().concat(ALREADY_FILTERED_SUFFIX);
|
||||
|
||||
|
||||
/**
|
||||
* This {@code doFilter} implementation stores a request attribute for
|
||||
* "already filtered", proceeding without filtering again if the
|
||||
* attribute is already there.
|
||||
*/
|
||||
@Override
|
||||
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
|
||||
throw new ServletException("OncePerRequestFilter just supports HTTP requests");
|
||||
}
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
boolean hasAlreadyFilteredAttribute = request.getAttribute(alreadyFilteredAttributeName) != null;
|
||||
|
||||
|
||||
if (hasAlreadyFilteredAttribute) {
|
||||
|
||||
// Proceed without invoking this filter...
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
else {
|
||||
// Do invoke this filter...
|
||||
request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
|
||||
try {
|
||||
doFilterInternal(httpRequest, httpResponse, filterChain);
|
||||
}
|
||||
finally {
|
||||
// Remove the "already filtered" request attribute for this request.
|
||||
request.removeAttribute(alreadyFilteredAttributeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Same contract as for {@code doFilter}, but guaranteed to be
|
||||
* just invoked once per request within a single request thread.
|
||||
* <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
|
||||
* default ServletRequest and ServletResponse ones.
|
||||
*/
|
||||
protected abstract void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException;
|
||||
|
||||
public void init(FilterConfig config) {}
|
||||
|
||||
public void destroy() {}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
/*
|
||||
* Copyright 2002-2013 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;
|
||||
|
||||
import org.springframework.session.Session;
|
||||
import org.springframework.session.SessionRepository;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.*;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Switches the {@link javax.servlet.http.HttpSession} implementation to be backed by a {@link org.springframework.session.Session}.
|
||||
*
|
||||
* The {@link SessionRepositoryFilter} wraps the {@link javax.servlet.http.HttpServletRequest} and overrides the methods
|
||||
* to get an {@link javax.servlet.http.HttpSession} to be backed by a {@link org.springframework.session.Session} returned
|
||||
* by the {@link org.springframework.session.SessionRepository}.
|
||||
*
|
||||
* The {@link SessionRepositoryFilter} uses a {@link HttpSessionStrategy} (default {@link CookieHttpSessionStrategy} to
|
||||
* bridge logic between an {@link javax.servlet.http.HttpSession} and the {@link org.springframework.session.Session}
|
||||
* abstraction. Specifically:
|
||||
*
|
||||
* <ul>
|
||||
* <li>The session id is looked up using {@link HttpSessionStrategy#getRequestedSessionId(javax.servlet.http.HttpServletRequest)}.
|
||||
* The default is to look in a cookie named SESSION.</li>
|
||||
* <li>The session id of newly created {@link org.springframework.session.Session} is sent to the client using
|
||||
* {@link HttpSessionStrategy#onNewSession(org.springframework.session.Session, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)} </li>
|
||||
* <li>The client is notified that the session id is no longer valid with {@link HttpSessionStrategy#onInvalidateSession(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* session id is looked up using the provided {@link HttpSessionStrategy}. The same strategy is used to convey the
|
||||
* session id of newly created {@link org.springframework.session.Session}s to the client.
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class SessionRepositoryFilter<S extends Session> extends OncePerRequestFilter {
|
||||
private final SessionRepository<S> sessionRepository;
|
||||
|
||||
private HttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy();
|
||||
|
||||
public SessionRepositoryFilter(SessionRepository<S> sessionRepository) {
|
||||
this.sessionRepository = sessionRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link HttpSessionStrategy} to be used. The default is a {@link CookieHttpSessionStrategy}.
|
||||
*
|
||||
* @param httpSessionStrategy the {@link HttpSessionStrategy} to use. Cannot be null.
|
||||
*/
|
||||
public void setHttpSessionStrategy(HttpSessionStrategy httpSessionStrategy) {
|
||||
Assert.notNull(httpSessionStrategy,"httpSessionIdStrategy cannot be null");
|
||||
this.httpSessionStrategy = httpSessionStrategy;
|
||||
}
|
||||
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(request, response);
|
||||
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(wrappedRequest,response);
|
||||
try {
|
||||
filterChain.doFilter(wrappedRequest, wrappedResponse);
|
||||
} finally {
|
||||
wrappedRequest.commitSession();
|
||||
}
|
||||
}
|
||||
|
||||
private final class SessionRepositoryResponseWrapper extends OnCommittedResponseWrapper {
|
||||
|
||||
private final SessionRepositoryRequestWrapper request;
|
||||
|
||||
/**
|
||||
* @param response the response to be wrapped
|
||||
*/
|
||||
public SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request, HttpServletResponse response) {
|
||||
super(response);
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResponseCommitted() {
|
||||
request.commitSession();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link javax.servlet.http.HttpServletRequest} that retrieves the {@link javax.servlet.http.HttpSession} using a
|
||||
* {@link org.springframework.session.SessionRepository}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 4.0
|
||||
*/
|
||||
private final class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper {
|
||||
private HttpSessionWrapper currentSession;
|
||||
private boolean requestedValidSession;
|
||||
private final HttpServletResponse response;
|
||||
|
||||
private SessionRepositoryRequestWrapper(HttpServletRequest request, HttpServletResponse response) {
|
||||
super(request);
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
private void commitSession() {
|
||||
HttpSessionWrapper wrappedSession = currentSession;
|
||||
if(wrappedSession == null) {
|
||||
if(isInvalidateClientSession()) {
|
||||
httpSessionStrategy.onInvalidateSession(this, response);
|
||||
}
|
||||
} else {
|
||||
S session = wrappedSession.session;
|
||||
sessionRepository.save(session);
|
||||
httpSessionStrategy.onNewSession(session, this, response);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isInvalidateClientSession() {
|
||||
return currentSession == null && requestedValidSession;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpSession getSession(boolean create) {
|
||||
if(currentSession != null) {
|
||||
return currentSession;
|
||||
}
|
||||
String requestedSessionId = getRequestedSessionId();
|
||||
if(requestedSessionId != null) {
|
||||
S session = sessionRepository.getSession(requestedSessionId);
|
||||
if(session != null) {
|
||||
this.requestedValidSession = true;
|
||||
session.setLastAccessedTime(System.currentTimeMillis());
|
||||
currentSession = new HttpSessionWrapper(session, getServletContext());
|
||||
currentSession.setNew(false);
|
||||
return currentSession;
|
||||
}
|
||||
}
|
||||
if(!create) {
|
||||
return null;
|
||||
}
|
||||
S session = sessionRepository.createSession();
|
||||
currentSession = new HttpSessionWrapper(session, getServletContext());
|
||||
return currentSession;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpSession getSession() {
|
||||
return getSession(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRequestedSessionId() {
|
||||
return httpSessionStrategy.getRequestedSessionId(this);
|
||||
}
|
||||
|
||||
private final class HttpSessionWrapper implements HttpSession {
|
||||
final S session;
|
||||
private final ServletContext servletContext;
|
||||
private boolean invalidated;
|
||||
private boolean old;
|
||||
|
||||
public HttpSessionWrapper(S session, ServletContext servletContext) {
|
||||
this.session = session;
|
||||
this.servletContext = servletContext;
|
||||
}
|
||||
|
||||
void updateLastAccessedTime() {
|
||||
checkState();
|
||||
session.setLastAccessedTime(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreationTime() {
|
||||
checkState();
|
||||
return session.getCreationTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return session.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getLastAccessedTime() {
|
||||
checkState();
|
||||
return session.getLastAccessedTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletContext getServletContext() {
|
||||
return servletContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMaxInactiveInterval(int interval) {
|
||||
session.setMaxInactiveInterval(interval);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxInactiveInterval() {
|
||||
return session.getMaxInactiveInterval();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpSessionContext getSessionContext() {
|
||||
return NOOP_SESSION_CONTEXT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getAttribute(String name) {
|
||||
checkState();
|
||||
return session.getAttribute(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValue(String name) {
|
||||
return getAttribute(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
checkState();
|
||||
return Collections.enumeration(session.getAttributeNames());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getValueNames() {
|
||||
checkState();
|
||||
Set<String> attrs = session.getAttributeNames();
|
||||
return attrs.toArray(new String[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttribute(String name, Object value) {
|
||||
checkState();
|
||||
session.setAttribute(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putValue(String name, Object value) {
|
||||
setAttribute(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAttribute(String name) {
|
||||
checkState();
|
||||
session.removeAttribute(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeValue(String name) {
|
||||
removeAttribute(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void invalidate() {
|
||||
checkState();
|
||||
this.invalidated = true;
|
||||
currentSession = null;
|
||||
sessionRepository.delete(getId());
|
||||
}
|
||||
|
||||
public void setNew(boolean isNew) {
|
||||
this.old = !isNew;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNew() {
|
||||
checkState();
|
||||
return !old;
|
||||
}
|
||||
|
||||
private void checkState() {
|
||||
if(invalidated) {
|
||||
throw new IllegalStateException("The HttpSession has already be invalidated.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final HttpSessionContext NOOP_SESSION_CONTEXT = new HttpSessionContext() {
|
||||
@Override
|
||||
public HttpSession getSession(String sessionId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<String> getIds() {
|
||||
return EMPTY_ENUMERATION;
|
||||
}
|
||||
};
|
||||
|
||||
private final static Enumeration<String> EMPTY_ENUMERATION = new Enumeration<String>() {
|
||||
@Override
|
||||
public boolean hasMoreElements() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String nextElement() {
|
||||
throw new NoSuchElementException("a");
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user