SEC-2781: Remove deprecations
This commit is contained in:
@@ -218,47 +218,6 @@ public class FilterChainProxy extends GenericFilterBean {
|
||||
return getFilters(firewall.getFirewalledRequest((new FilterInvocation(url, null).getRequest())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the mapping of URL patterns to filter chains.
|
||||
*
|
||||
* The map keys should be the paths and the values should be arrays of {@code Filter} objects.
|
||||
* It's VERY important that the type of map used preserves ordering - the order in which the iterator
|
||||
* returns the entries must be the same as the order they were added to the map, otherwise you have no way
|
||||
* of guaranteeing that the most specific patterns are returned before the more general ones. So make sure
|
||||
* the Map used is an instance of {@code LinkedHashMap} or an equivalent, rather than a plain {@code HashMap}, for
|
||||
* example.
|
||||
*
|
||||
* @param filterChainMap the map of path Strings to {@code List<Filter>}s.
|
||||
* @deprecated Use the constructor which takes a {@code List<SecurityFilterChain>} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public void setFilterChainMap(Map<RequestMatcher, List<Filter>> filterChainMap) {
|
||||
filterChains = new ArrayList<SecurityFilterChain>(filterChainMap.size());
|
||||
|
||||
for (Map.Entry<RequestMatcher,List<Filter>> entry : filterChainMap.entrySet()) {
|
||||
filterChains.add(new DefaultSecurityFilterChain(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the underlying filter chain map. Modifications to the map contents
|
||||
* will not affect the FilterChainProxy state.
|
||||
*
|
||||
* @return the map of path pattern Strings to filter chain lists (with ordering guaranteed).
|
||||
*
|
||||
* @deprecated use the list of {@link SecurityFilterChain}s instead
|
||||
*/
|
||||
@Deprecated
|
||||
public Map<RequestMatcher, List<Filter>> getFilterChainMap() {
|
||||
LinkedHashMap<RequestMatcher, List<Filter>> map = new LinkedHashMap<RequestMatcher, List<Filter>>();
|
||||
|
||||
for (SecurityFilterChain chain : filterChains) {
|
||||
map.put(((DefaultSecurityFilterChain)chain).getRequestMatcher(), chain.getFilters());
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the list of {@code SecurityFilterChain}s which will be matched against and
|
||||
* applied to incoming requests.
|
||||
|
||||
-27
@@ -79,13 +79,6 @@ public class ExceptionTranslationFilter extends GenericFilterBean {
|
||||
|
||||
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public ExceptionTranslationFilter() {
|
||||
}
|
||||
|
||||
public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
this(authenticationEntryPoint, new HttpSessionRequestCache());
|
||||
}
|
||||
@@ -191,14 +184,6 @@ public class ExceptionTranslationFilter extends GenericFilterBean {
|
||||
this.accessDeniedHandler = accessDeniedHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor
|
||||
*/
|
||||
@Deprecated
|
||||
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
this.authenticationEntryPoint = authenticationEntryPoint;
|
||||
}
|
||||
|
||||
public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver) {
|
||||
Assert.notNull(authenticationTrustResolver, "authenticationTrustResolver must not be null");
|
||||
this.authenticationTrustResolver = authenticationTrustResolver;
|
||||
@@ -209,18 +194,6 @@ public class ExceptionTranslationFilter extends GenericFilterBean {
|
||||
this.throwableAnalyzer = throwableAnalyzer;
|
||||
}
|
||||
|
||||
/**
|
||||
* The RequestCache implementation used to store the current request before starting authentication.
|
||||
* Defaults to an {@link HttpSessionRequestCache}.
|
||||
*
|
||||
* @deprecated Use constructor
|
||||
*/
|
||||
@Deprecated
|
||||
public void setRequestCache(RequestCache requestCache) {
|
||||
Assert.notNull(requestCache, "requestCache cannot be null");
|
||||
this.requestCache = requestCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation of <code>ThrowableAnalyzer</code> which is capable of also unwrapping
|
||||
* <code>ServletException</code>s.
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ import org.springframework.web.filter.GenericFilterBean;
|
||||
<bean id="channelProcessingFilter" class="org.springframework.security.web.access.channel.ChannelProcessingFilter">
|
||||
<property name="channelDecisionManager" ref="channelDecisionManager"/>
|
||||
<property name="securityMetadataSource">
|
||||
<security:filter-security-metadata-source path-type="regex">
|
||||
<security:filter-security-metadata-source request-matcher="regex">
|
||||
<security:intercept-url pattern="\A/secure/.*\Z" access="REQUIRES_SECURE_CHANNEL"/>
|
||||
<security:intercept-url pattern="\A/login.jsp.*\Z" access="REQUIRES_SECURE_CHANNEL"/>
|
||||
<security:intercept-url pattern="\A/.*\Z" access="ANY_CHANNEL"/>
|
||||
|
||||
+2
-2
@@ -1,6 +1,7 @@
|
||||
package org.springframework.security.web.access.expression;
|
||||
|
||||
import org.springframework.security.access.expression.AbstractSecurityExpressionHandler;
|
||||
import org.springframework.security.access.expression.SecurityExpressionHandler;
|
||||
import org.springframework.security.access.expression.SecurityExpressionOperations;
|
||||
import org.springframework.security.authentication.AuthenticationTrustResolver;
|
||||
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
|
||||
@@ -13,8 +14,7 @@ import org.springframework.util.Assert;
|
||||
* @author Luke Taylor
|
||||
* @since 3.0
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class DefaultWebSecurityExpressionHandler extends AbstractSecurityExpressionHandler<FilterInvocation> implements WebSecurityExpressionHandler {
|
||||
public class DefaultWebSecurityExpressionHandler extends AbstractSecurityExpressionHandler<FilterInvocation> implements SecurityExpressionHandler<FilterInvocation> {
|
||||
|
||||
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
|
||||
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package org.springframework.security.web.access.expression;
|
||||
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
import org.springframework.security.access.expression.SecurityExpressionHandler;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
|
||||
@Deprecated
|
||||
public interface WebSecurityExpressionHandler extends SecurityExpressionHandler<FilterInvocation> {
|
||||
|
||||
EvaluationContext createEvaluationContext(Authentication authentication, FilterInvocation invocation);
|
||||
}
|
||||
+8
-79
@@ -40,6 +40,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.WebAttributes;
|
||||
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.security.web.util.UrlUtils;
|
||||
import org.springframework.util.Assert;
|
||||
@@ -72,8 +73,8 @@ import org.springframework.web.filter.GenericFilterBean;
|
||||
* therein. Otherwise it will redirect to the webapp root "/". You can customize this behaviour by injecting a
|
||||
* differently configured instance of this class, or by using a different implementation.
|
||||
* <p>
|
||||
* See the {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, Authentication)
|
||||
* successfulAuthentication} method for more information.
|
||||
* See the {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)}
|
||||
* method for more information.
|
||||
*
|
||||
* <h4>Authentication Failure</h4>
|
||||
*
|
||||
@@ -102,12 +103,6 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
ApplicationEventPublisherAware, MessageSourceAware {
|
||||
//~ Static fields/initializers =====================================================================================
|
||||
|
||||
/**
|
||||
* @deprecated Use the value in {@link WebAttributes} directly.
|
||||
*/
|
||||
@Deprecated
|
||||
public static final String SPRING_SECURITY_LAST_EXCEPTION_KEY = WebAttributes.AUTHENTICATION_EXCEPTION;
|
||||
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
protected ApplicationEventPublisher eventPublisher;
|
||||
@@ -118,14 +113,6 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
|
||||
private RequestMatcher requiresAuthenticationRequestMatcher;
|
||||
|
||||
/**
|
||||
* The URL destination that this filter intercepts and processes (usually
|
||||
* something like <code>/j_spring_security_check</code>)
|
||||
* @deprecated use {@link #requiresAuthenticationRequestMatcher} instead
|
||||
*/
|
||||
@Deprecated
|
||||
private String filterProcessesUrl;
|
||||
|
||||
private boolean continueChainBeforeSuccessfulAuthentication = false;
|
||||
|
||||
private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy();
|
||||
@@ -141,8 +128,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
* @param defaultFilterProcessesUrl the default value for <tt>filterProcessesUrl</tt>.
|
||||
*/
|
||||
protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl) {
|
||||
this.requiresAuthenticationRequestMatcher = new FilterProcessUrlRequestMatcher(defaultFilterProcessesUrl);
|
||||
this.filterProcessesUrl = defaultFilterProcessesUrl;
|
||||
setFilterProcessesUrl(defaultFilterProcessesUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -178,8 +164,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
* <li>An <tt>Authentication</tt> object is returned.
|
||||
* The configured {@link SessionAuthenticationStrategy} will be invoked (to handle any session-related behaviour
|
||||
* such as creating a new session to protect against session-fixation attacks) followed by the invocation of
|
||||
* {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, Authentication)
|
||||
* successfulAuthentication} method</li>
|
||||
* {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} method</li>
|
||||
* <li>An <tt>AuthenticationException</tt> occurs during authentication.
|
||||
* The {@link #unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException)
|
||||
* unsuccessfulAuthentication} method will be invoked</li>
|
||||
@@ -246,9 +231,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
* Subclasses may override for special requirements, such as Tapestry integration.
|
||||
*
|
||||
* @return <code>true</code> if the filter should attempt authentication, <code>false</code> otherwise.
|
||||
* @deprecated use {@link #setRequiresAuthenticationRequestMatcher(RequestMatcher)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
|
||||
return requiresAuthenticationRequestMatcher.matches(request);
|
||||
}
|
||||
@@ -294,25 +277,6 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
* @throws ServletException
|
||||
*/
|
||||
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
|
||||
Authentication authResult) throws IOException, ServletException{
|
||||
successfulAuthentication(request, response, authResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Default behaviour for successful authentication.
|
||||
* <ol>
|
||||
* <li>Sets the successful <tt>Authentication</tt> object on the {@link SecurityContextHolder}</li>
|
||||
* <li>Informs the configured <tt>RememberMeServices</tt> of the successful login</li>
|
||||
* <li>Fires an {@link InteractiveAuthenticationSuccessEvent} via the configured
|
||||
* <tt>ApplicationEventPublisher</tt></li>
|
||||
* <li>Delegates additional behaviour to the {@link AuthenticationSuccessHandler}.</li>
|
||||
* </ol>
|
||||
*
|
||||
* @param authResult the object returned from the <tt>attemptAuthentication</tt> method.
|
||||
* @deprecated since 3.1. Use {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
||||
Authentication authResult) throws IOException, ServletException {
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
@@ -363,26 +327,17 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public String getFilterProcessesUrl() {
|
||||
return filterProcessesUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the URL that determines if authentication is required
|
||||
*
|
||||
* @param filterProcessesUrl
|
||||
* @deprecated use {@link #setRequiresAuthenticationRequestMatcher(RequestMatcher)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public void setFilterProcessesUrl(String filterProcessesUrl) {
|
||||
this.requiresAuthenticationRequestMatcher = new FilterProcessUrlRequestMatcher(filterProcessesUrl);
|
||||
this.filterProcessesUrl = filterProcessesUrl;
|
||||
setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(filterProcessesUrl));
|
||||
}
|
||||
|
||||
public final void setRequiresAuthenticationRequestMatcher(RequestMatcher requestMatcher) {
|
||||
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
|
||||
this.filterProcessesUrl = null;
|
||||
this.requiresAuthenticationRequestMatcher = requestMatcher;
|
||||
}
|
||||
|
||||
@@ -397,8 +352,8 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
|
||||
/**
|
||||
* Indicates if the filter chain should be continued prior to delegation to
|
||||
* {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse,
|
||||
* Authentication)}, which may be useful in certain environment (such as
|
||||
* {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)}, which
|
||||
* may be useful in certain environment (such as
|
||||
* Tapestry applications). Defaults to <code>false</code>.
|
||||
*/
|
||||
public void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication) {
|
||||
@@ -459,30 +414,4 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
|
||||
protected AuthenticationFailureHandler getFailureHandler() {
|
||||
return failureHandler;
|
||||
}
|
||||
|
||||
private static final class FilterProcessUrlRequestMatcher implements RequestMatcher {
|
||||
private final String filterProcessesUrl;
|
||||
|
||||
private FilterProcessUrlRequestMatcher(String filterProcessesUrl) {
|
||||
Assert.hasLength(filterProcessesUrl, "filterProcessesUrl must be specified");
|
||||
Assert.isTrue(UrlUtils.isValidRedirectUrl(filterProcessesUrl), filterProcessesUrl + " isn't a valid redirect URL");
|
||||
this.filterProcessesUrl = filterProcessesUrl;
|
||||
}
|
||||
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
int pathParamIndex = uri.indexOf(';');
|
||||
|
||||
if (pathParamIndex > 0) {
|
||||
// strip everything after the first semi-colon
|
||||
uri = uri.substring(0, pathParamIndex);
|
||||
}
|
||||
|
||||
if ("".equals(request.getContextPath())) {
|
||||
return uri.endsWith(filterProcessesUrl);
|
||||
}
|
||||
|
||||
return uri.endsWith(request.getContextPath() + filterProcessesUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-55
@@ -54,13 +54,6 @@ public class AnonymousAuthenticationFilter extends GenericFilterBean implements
|
||||
private Object principal;
|
||||
private List<GrantedAuthority> authorities;
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection version
|
||||
*/
|
||||
@Deprecated
|
||||
public AnonymousAuthenticationFilter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a filter with a principal named "anonymousUser" and the single authority "ROLE_ANONYMOUS".
|
||||
*
|
||||
@@ -77,6 +70,9 @@ public class AnonymousAuthenticationFilter extends GenericFilterBean implements
|
||||
* @param authorities the authority list for anonymous users
|
||||
*/
|
||||
public AnonymousAuthenticationFilter(String key, Object principal, List<GrantedAuthority> authorities) {
|
||||
Assert.hasLength(key, "key cannot be null or empty");
|
||||
Assert.notNull(principal, "Anonymous authentication principal must be set");
|
||||
Assert.notNull(authorities, "Anonymous authorities must be set");
|
||||
this.key = key;
|
||||
this.principal = principal;
|
||||
this.authorities = authorities;
|
||||
@@ -94,42 +90,23 @@ public class AnonymousAuthenticationFilter extends GenericFilterBean implements
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
|
||||
if (applyAnonymousForThisRequest((HttpServletRequest) req)) {
|
||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));
|
||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Populated SecurityContextHolder with anonymous token: '"
|
||||
+ SecurityContextHolder.getContext().getAuthentication() + "'");
|
||||
}
|
||||
} else {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("SecurityContextHolder not populated with anonymous token, as it already contained: '"
|
||||
+ SecurityContextHolder.getContext().getAuthentication() + "'");
|
||||
}
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Populated SecurityContextHolder with anonymous token: '"
|
||||
+ SecurityContextHolder.getContext().getAuthentication() + "'");
|
||||
}
|
||||
} else {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("SecurityContextHolder not populated with anonymous token, as it already contained: '"
|
||||
+ SecurityContextHolder.getContext().getAuthentication() + "'");
|
||||
}
|
||||
}
|
||||
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables subclasses to determine whether or not an anonymous authentication token should be setup for
|
||||
* this request. This is useful if anonymous authentication should be allowed only for specific IP subnet ranges
|
||||
* etc.
|
||||
*
|
||||
* @param request to assist the method determine request details
|
||||
*
|
||||
* @return <code>true</code> if the anonymous token should be setup for this request (provided that the request
|
||||
* doesn't already have some other <code>Authentication</code> inside it), or <code>false</code> if no
|
||||
* anonymous token should be setup for this request
|
||||
* @deprecated no obvious use case and can easily be achieved by other means
|
||||
*/
|
||||
@Deprecated
|
||||
protected boolean applyAnonymousForThisRequest(HttpServletRequest request) {
|
||||
return true;
|
||||
}
|
||||
|
||||
protected Authentication createAuthentication(HttpServletRequest request) {
|
||||
AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key, principal, authorities);
|
||||
auth.setDetails(authenticationDetailsSource.buildDetails(request));
|
||||
@@ -149,23 +126,4 @@ public class AnonymousAuthenticationFilter extends GenericFilterBean implements
|
||||
public List<GrantedAuthority> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @deprecated use constructor injection instead
|
||||
*/
|
||||
@Deprecated
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @deprecated use constructor injection instead
|
||||
*/
|
||||
@Deprecated
|
||||
public void setUserAttribute(UserAttribute userAttributeDefinition) {
|
||||
this.principal = userAttributeDefinition.getPassword();
|
||||
this.authorities = userAttributeDefinition.getAuthorities();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-19
@@ -81,19 +81,13 @@ public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoin
|
||||
|
||||
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public LoginUrlAuthenticationEntryPoint() {
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param loginFormUrl URL where the login page can be found. Should either be relative to the web-app context path
|
||||
* (include a leading {@code /}) or an absolute URL.
|
||||
*/
|
||||
public LoginUrlAuthenticationEntryPoint(String loginFormUrl) {
|
||||
Assert.notNull(loginFormUrl,"loginFormUrl cannot be null");
|
||||
this.loginFormUrl = loginFormUrl;
|
||||
}
|
||||
|
||||
@@ -240,23 +234,12 @@ public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoin
|
||||
return forceHttps;
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL where the <code>UsernamePasswordAuthenticationFilter</code> login
|
||||
* page can be found. Should either be relative to the web-app context path
|
||||
* (include a leading {@code /}) or an absolute URL.
|
||||
*
|
||||
* @deprecated use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setLoginFormUrl(String loginFormUrl) {
|
||||
this.loginFormUrl = loginFormUrl;
|
||||
}
|
||||
|
||||
public String getLoginFormUrl() {
|
||||
return loginFormUrl;
|
||||
}
|
||||
|
||||
public void setPortMapper(PortMapper portMapper) {
|
||||
Assert.notNull(portMapper, "portMapper cannot be null");
|
||||
this.portMapper = portMapper;
|
||||
}
|
||||
|
||||
@@ -265,6 +248,7 @@ public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoin
|
||||
}
|
||||
|
||||
public void setPortResolver(PortResolver portResolver) {
|
||||
Assert.notNull(portResolver, "portResolver cannot be null");
|
||||
this.portResolver = portResolver;
|
||||
}
|
||||
|
||||
|
||||
-5
@@ -50,11 +50,6 @@ public class UsernamePasswordAuthenticationFilter extends AbstractAuthentication
|
||||
|
||||
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
|
||||
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
|
||||
/**
|
||||
* @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
|
||||
|
||||
private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
|
||||
private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
|
||||
|
||||
+2
-43
@@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.security.web.util.UrlUtils;
|
||||
import org.springframework.util.Assert;
|
||||
@@ -50,7 +51,6 @@ public class LogoutFilter extends GenericFilterBean {
|
||||
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private String filterProcessesUrl;
|
||||
private RequestMatcher logoutRequestMatcher;
|
||||
|
||||
private final List<LogoutHandler> handlers;
|
||||
@@ -125,50 +125,9 @@ public class LogoutFilter extends GenericFilterBean {
|
||||
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) {
|
||||
Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null");
|
||||
this.logoutRequestMatcher = logoutRequestMatcher;
|
||||
this.filterProcessesUrl = null;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setFilterProcessesUrl(String filterProcessesUrl) {
|
||||
this.logoutRequestMatcher = new FilterProcessUrlRequestMatcher(filterProcessesUrl);
|
||||
this.filterProcessesUrl = filterProcessesUrl;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
protected String getFilterProcessesUrl() {
|
||||
return filterProcessesUrl;
|
||||
}
|
||||
|
||||
private static final class FilterProcessUrlRequestMatcher implements RequestMatcher {
|
||||
private final String filterProcessesUrl;
|
||||
|
||||
private FilterProcessUrlRequestMatcher(String filterProcessesUrl) {
|
||||
Assert.hasLength(filterProcessesUrl, "filterProcessesUrl must be specified");
|
||||
Assert.isTrue(UrlUtils.isValidRedirectUrl(filterProcessesUrl), filterProcessesUrl + " isn't a valid redirect URL");
|
||||
this.filterProcessesUrl = filterProcessesUrl;
|
||||
}
|
||||
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
int pathParamIndex = uri.indexOf(';');
|
||||
|
||||
if (pathParamIndex > 0) {
|
||||
// strip everything from the first semi-colon
|
||||
uri = uri.substring(0, pathParamIndex);
|
||||
}
|
||||
|
||||
int queryParamIndex = uri.indexOf('?');
|
||||
|
||||
if (queryParamIndex > 0) {
|
||||
// strip everything from the first question mark
|
||||
uri = uri.substring(0, queryParamIndex);
|
||||
}
|
||||
|
||||
if ("".equals(request.getContextPath())) {
|
||||
return uri.endsWith(filterProcessesUrl);
|
||||
}
|
||||
|
||||
return uri.endsWith(request.getContextPath() + filterProcessesUrl);
|
||||
}
|
||||
this.logoutRequestMatcher = new AntPathRequestMatcher(filterProcessesUrl);
|
||||
}
|
||||
}
|
||||
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
package org.springframework.security.web.authentication.preauth;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationDetails;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.MutableGrantedAuthoritiesContainer;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* This AuthenticationDetails implementation allows for storing a list of
|
||||
* pre-authenticated Granted Authorities.
|
||||
*
|
||||
* @author Ruud Senden
|
||||
* @since 2.0
|
||||
*/
|
||||
@Deprecated
|
||||
public class PreAuthenticatedGrantedAuthoritiesAuthenticationDetails extends AuthenticationDetails implements
|
||||
MutableGrantedAuthoritiesContainer {
|
||||
public static final long serialVersionUID = 1L;
|
||||
|
||||
private List<GrantedAuthority> preAuthenticatedGrantedAuthorities = null;
|
||||
|
||||
public PreAuthenticatedGrantedAuthoritiesAuthenticationDetails(Object context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @see org.springframework.security.core.authority.GrantedAuthoritiesContainer#getGrantedAuthorities()
|
||||
*/
|
||||
public List<GrantedAuthority> getGrantedAuthorities() {
|
||||
Assert.notNull(preAuthenticatedGrantedAuthorities, "Pre-authenticated granted authorities have not been set");
|
||||
|
||||
return preAuthenticatedGrantedAuthorities;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see MutableGrantedAuthoritiesContainer#setGrantedAuthorities(Collection)
|
||||
*/
|
||||
public void setGrantedAuthorities(Collection<? extends GrantedAuthority> aJ2eeBasedGrantedAuthorities) {
|
||||
List<GrantedAuthority> temp = new ArrayList<GrantedAuthority>(aJ2eeBasedGrantedAuthorities.size());
|
||||
temp.addAll(aJ2eeBasedGrantedAuthorities);
|
||||
this.preAuthenticatedGrantedAuthorities = Collections.unmodifiableList(temp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The String representation of this object.
|
||||
*/
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(super.toString()).append("; ");
|
||||
sb.append("preAuthenticatedGrantedAuthorities: ").append(preAuthenticatedGrantedAuthorities);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
-13
@@ -52,19 +52,6 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsService
|
||||
* @param authorities the pre-authenticated authorities.
|
||||
*/
|
||||
protected UserDetails createUserDetails(Authentication token, Collection<? extends GrantedAuthority> authorities) {
|
||||
return createuserDetails(token, authorities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the final <tt>UserDetails</tt> object. Can be overridden to customize the contents.
|
||||
*
|
||||
* @deprecated Use {@link #createUserDetails(Authentication, Collection)}
|
||||
*
|
||||
* @param token the authentication request token
|
||||
* @param authorities the pre-authenticated authorities.
|
||||
*/
|
||||
@Deprecated
|
||||
protected UserDetails createuserDetails(Authentication token, Collection<? extends GrantedAuthority> authorities) {
|
||||
return new User(token.getName(), "N/A", true, true, true, true, authorities);
|
||||
}
|
||||
}
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
package org.springframework.security.web.authentication.preauth.websphere;
|
||||
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.security.authentication.AuthenticationDetailsSource;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* This method interceptor can be used in front of arbitrary Spring beans to make a Spring SecurityContext
|
||||
* available to the bean, based on the current WebSphere credentials.
|
||||
*
|
||||
* @author Ruud Senden
|
||||
* @since 1.0
|
||||
*/
|
||||
@Deprecated
|
||||
public class WebSphere2SpringSecurityPropagationInterceptor implements MethodInterceptor {
|
||||
private static final Log logger = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class);
|
||||
private AuthenticationManager authenticationManager = null;
|
||||
private AuthenticationDetailsSource<?,?> authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource();
|
||||
private final WASUsernameAndGroupsExtractor wasHelper;
|
||||
|
||||
public WebSphere2SpringSecurityPropagationInterceptor() {
|
||||
this(new DefaultWASUsernameAndGroupsExtractor());
|
||||
}
|
||||
|
||||
WebSphere2SpringSecurityPropagationInterceptor(WASUsernameAndGroupsExtractor wasHelper) {
|
||||
this.wasHelper = wasHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate with Spring Security based on WebSphere credentials before proceeding with method
|
||||
* invocation, and clean up the Spring Security Context after method invocation finishes.
|
||||
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
|
||||
*/
|
||||
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
|
||||
try {
|
||||
logger.debug("Performing Spring Security authentication with WebSphere credentials");
|
||||
authenticateSpringSecurityWithWASCredentials();
|
||||
logger.debug("Proceeding with method invocation");
|
||||
return methodInvocation.proceed();
|
||||
} finally {
|
||||
logger.debug("Clearing Spring Security security context");
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the current WebSphere credentials and authenticate them with Spring Security
|
||||
* using the pre-authenticated authentication provider.
|
||||
*/
|
||||
private void authenticateSpringSecurityWithWASCredentials() {
|
||||
Assert.notNull(authenticationManager);
|
||||
Assert.notNull(authenticationDetailsSource);
|
||||
|
||||
String userName = wasHelper.getCurrentUserName();
|
||||
if (logger.isDebugEnabled()) { logger.debug("Creating authentication request for user "+userName); }
|
||||
PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName, "N/A");
|
||||
authRequest.setDetails(authenticationDetailsSource.buildDetails(null));
|
||||
if (logger.isDebugEnabled()) { logger.debug("Authentication request for user "+userName+": "+authRequest); }
|
||||
Authentication authResponse = authenticationManager.authenticate(authRequest);
|
||||
if (logger.isDebugEnabled()) { logger.debug("Authentication response for user "+userName+": "+authResponse); }
|
||||
SecurityContextHolder.getContext().setAuthentication(authResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param authenticationManager The authenticationManager to set.
|
||||
*/
|
||||
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param authenticationDetailsSource The authenticationDetailsSource to set.
|
||||
*/
|
||||
public void setAuthenticationDetailsSource(AuthenticationDetailsSource<?,?> authenticationDetailsSource) {
|
||||
this.authenticationDetailsSource = authenticationDetailsSource;
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package org.springframework.security.web.authentication.preauth.websphere;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.security.authentication.AuthenticationDetailsSourceImpl;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.MutableGrantedAuthoritiesContainer;
|
||||
import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper;
|
||||
import org.springframework.security.core.authority.mapping.SimpleAttributes2GrantedAuthoritiesMapper;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesAuthenticationDetails;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* This AuthenticationDetailsSource implementation, when configured with a MutableGrantedAuthoritiesContainer,
|
||||
* will set the pre-authenticated granted authorities based on the WebSphere groups for the current WebSphere
|
||||
* user, mapped using the configured Attributes2GrantedAuthoritiesMapper.
|
||||
*
|
||||
* By default, this class is configured to build instances of the
|
||||
* PreAuthenticatedGrantedAuthoritiesAuthenticationDetails class.
|
||||
*
|
||||
* @author Ruud Senden
|
||||
*/
|
||||
@Deprecated
|
||||
public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl implements InitializingBean {
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private Attributes2GrantedAuthoritiesMapper webSphereGroups2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
|
||||
private final WASUsernameAndGroupsExtractor wasHelper;
|
||||
|
||||
/**
|
||||
* Public constructor which overrides the default AuthenticationDetails
|
||||
* class to be used.
|
||||
*/
|
||||
public WebSpherePreAuthenticatedAuthenticationDetailsSource() {
|
||||
this(new DefaultWASUsernameAndGroupsExtractor());
|
||||
}
|
||||
|
||||
WebSpherePreAuthenticatedAuthenticationDetailsSource(WASUsernameAndGroupsExtractor wasHelper) {
|
||||
super.setClazz(PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.class);
|
||||
this.wasHelper = wasHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that all required properties have been set.
|
||||
*/
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
Assert.notNull(webSphereGroups2GrantedAuthoritiesMapper, "WebSphere groups to granted authorities mapper not set");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the authentication details object. If the specified authentication
|
||||
* details class implements the PreAuthenticatedGrantedAuthoritiesSetter, a
|
||||
* list of pre-authenticated Granted Authorities will be set based on the
|
||||
* WebSphere groups for the current user.
|
||||
*
|
||||
* @see org.springframework.security.authentication.AuthenticationDetailsSource#buildDetails(Object)
|
||||
*/
|
||||
public Object buildDetails(Object context) {
|
||||
Object result = super.buildDetails(context);
|
||||
if (result instanceof MutableGrantedAuthoritiesContainer) {
|
||||
((MutableGrantedAuthoritiesContainer) result)
|
||||
.setGrantedAuthorities(getWebSphereGroupsBasedGrantedAuthorities());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of Granted Authorities based on the current user's WebSphere groups.
|
||||
*
|
||||
* @return authorities mapped from the user's WebSphere groups.
|
||||
*/
|
||||
private Collection<? extends GrantedAuthority> getWebSphereGroupsBasedGrantedAuthorities() {
|
||||
List<String> webSphereGroups = wasHelper.getGroupsForCurrentUser();
|
||||
Collection<? extends GrantedAuthority> userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " + userGas);
|
||||
}
|
||||
return userGas;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mapper
|
||||
* The Attributes2GrantedAuthoritiesMapper to use
|
||||
*/
|
||||
public void setWebSphereGroups2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
|
||||
webSphereGroups2GrantedAuthoritiesMapper = mapper;
|
||||
}
|
||||
|
||||
}
|
||||
-27
@@ -64,14 +64,6 @@ public abstract class AbstractRememberMeServices implements RememberMeServices,
|
||||
private Method setHttpOnlyMethod;
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
protected AbstractRememberMeServices() {
|
||||
this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class,"setHttpOnly", boolean.class);
|
||||
}
|
||||
|
||||
protected AbstractRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||
Assert.hasLength(key, "key cannot be empty or null");
|
||||
Assert.notNull(userDetailsService, "UserDetailsService cannot be null");
|
||||
@@ -412,25 +404,6 @@ public abstract class AbstractRememberMeServices implements RememberMeServices,
|
||||
return userDetailsService;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setUserDetailsService(UserDetailsService userDetailsService) {
|
||||
Assert.notNull(userDetailsService, "UserDetailsService cannot be null");
|
||||
this.userDetailsService = userDetailsService;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
-16
@@ -49,14 +49,6 @@ public class PersistentTokenBasedRememberMeServices extends AbstractRememberMeSe
|
||||
private int seriesLength = DEFAULT_SERIES_LENGTH;
|
||||
private int tokenLength = DEFAULT_TOKEN_LENGTH;
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public PersistentTokenBasedRememberMeServices() {
|
||||
random = new SecureRandom();
|
||||
}
|
||||
|
||||
public PersistentTokenBasedRememberMeServices(String key, UserDetailsService userDetailsService,
|
||||
PersistentTokenRepository tokenRepository) {
|
||||
super(key, userDetailsService);
|
||||
@@ -172,14 +164,6 @@ public class PersistentTokenBasedRememberMeServices extends AbstractRememberMeSe
|
||||
setCookie(new String[] {token.getSeries(), token.getTokenValue()}, getTokenValiditySeconds(), request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setTokenRepository(PersistentTokenRepository tokenRepository) {
|
||||
this.tokenRepository = tokenRepository;
|
||||
}
|
||||
|
||||
public void setSeriesLength(int seriesLength) {
|
||||
this.seriesLength = seriesLength;
|
||||
}
|
||||
|
||||
+2
-23
@@ -67,15 +67,10 @@ public class RememberMeAuthenticationFilter extends GenericFilterBean implements
|
||||
private AuthenticationManager authenticationManager;
|
||||
private RememberMeServices rememberMeServices;
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public RememberMeAuthenticationFilter() {
|
||||
}
|
||||
|
||||
public RememberMeAuthenticationFilter(AuthenticationManager authenticationManager,
|
||||
RememberMeServices rememberMeServices) {
|
||||
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
|
||||
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.rememberMeServices = rememberMeServices;
|
||||
}
|
||||
@@ -172,22 +167,6 @@ public class RememberMeAuthenticationFilter extends GenericFilterBean implements
|
||||
this.eventPublisher = eventPublisher;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setRememberMeServices(RememberMeServices rememberMeServices) {
|
||||
this.rememberMeServices = rememberMeServices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows control over the destination a remembered user is sent to when they are successfully authenticated.
|
||||
* By default, the filter will just allow the current request to proceed, but if an
|
||||
|
||||
-7
@@ -82,13 +82,6 @@ import java.util.Date;
|
||||
*/
|
||||
public class TokenBasedRememberMeServices extends AbstractRememberMeServices {
|
||||
|
||||
/**
|
||||
* @deprecated Use with-args constructor
|
||||
*/
|
||||
@Deprecated
|
||||
public TokenBasedRememberMeServices() {
|
||||
}
|
||||
|
||||
public TokenBasedRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||
super(key, userDetailsService);
|
||||
}
|
||||
|
||||
-182
@@ -1,182 +0,0 @@
|
||||
package org.springframework.security.web.authentication.session;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.MessageSourceAware;
|
||||
import org.springframework.context.support.MessageSourceAccessor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.SpringSecurityMessageSource;
|
||||
import org.springframework.security.core.session.SessionInformation;
|
||||
import org.springframework.security.core.session.SessionRegistry;
|
||||
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.security.web.session.ConcurrentSessionFilter;
|
||||
import org.springframework.security.web.session.SessionManagementFilter;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Strategy which handles concurrent session-control, in addition to the functionality provided by the base class.
|
||||
*
|
||||
* When invoked following an authentication, it will check whether the user in question should be allowed to proceed,
|
||||
* by comparing the number of sessions they already have active with the configured <tt>maximumSessions</tt> value.
|
||||
* The {@link SessionRegistry} is used as the source of data on authenticated users and session data.
|
||||
* <p>
|
||||
* If a user has reached the maximum number of permitted sessions, the behaviour depends on the
|
||||
* <tt>exceptionIfMaxExceeded</tt> property. The default behaviour is to expired the least recently used session, which
|
||||
* will be invalidated by the {@link ConcurrentSessionFilter} if accessed again. If <tt>exceptionIfMaxExceeded</tt> is
|
||||
* set to <tt>true</tt>, however, the user will be prevented from starting a new authenticated session.
|
||||
* <p>
|
||||
* This strategy can be injected into both the {@link SessionManagementFilter} and instances of
|
||||
* {@link AbstractAuthenticationProcessingFilter} (typically {@link UsernamePasswordAuthenticationFilter}).
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @since 3.0
|
||||
* @deprecated Use {@link ConcurrentSessionControlAuthenticationStrategy} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public class ConcurrentSessionControlStrategy extends SessionFixationProtectionStrategy
|
||||
implements MessageSourceAware {
|
||||
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
private final SessionRegistry sessionRegistry;
|
||||
private boolean exceptionIfMaximumExceeded = false;
|
||||
private int maximumSessions = 1;
|
||||
|
||||
/**
|
||||
* @param sessionRegistry the session registry which should be updated when the authenticated session is changed.
|
||||
*/
|
||||
public ConcurrentSessionControlStrategy(SessionRegistry sessionRegistry) {
|
||||
Assert.notNull(sessionRegistry, "The sessionRegistry cannot be null");
|
||||
super.setAlwaysCreateSession(true);
|
||||
this.sessionRegistry = sessionRegistry;
|
||||
}
|
||||
|
||||
/**
|
||||
* In addition to the steps from the superclass, the sessionRegistry will be updated with the new session information.
|
||||
*/
|
||||
@Override
|
||||
public void onAuthentication(Authentication authentication, HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
checkAuthenticationAllowed(authentication, request);
|
||||
|
||||
// Allow the parent to create a new session if necessary
|
||||
super.onAuthentication(authentication, request, response);
|
||||
sessionRegistry.registerNewSession(request.getSession().getId(), authentication.getPrincipal());
|
||||
}
|
||||
|
||||
private void checkAuthenticationAllowed(Authentication authentication, HttpServletRequest request)
|
||||
throws AuthenticationException {
|
||||
|
||||
final List<SessionInformation> sessions = sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
|
||||
|
||||
int sessionCount = sessions.size();
|
||||
int allowedSessions = getMaximumSessionsForThisUser(authentication);
|
||||
|
||||
if (sessionCount < allowedSessions) {
|
||||
// They haven't got too many login sessions running at present
|
||||
return;
|
||||
}
|
||||
|
||||
if (allowedSessions == -1) {
|
||||
// We permit unlimited logins
|
||||
return;
|
||||
}
|
||||
|
||||
if (sessionCount == allowedSessions) {
|
||||
HttpSession session = request.getSession(false);
|
||||
|
||||
if (session != null) {
|
||||
// Only permit it though if this request is associated with one of the already registered sessions
|
||||
for (SessionInformation si : sessions) {
|
||||
if (si.getSessionId().equals(session.getId())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If the session is null, a new one will be created by the parent class, exceeding the allowed number
|
||||
}
|
||||
|
||||
allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method intended for use by subclasses to override the maximum number of sessions that are permitted for
|
||||
* a particular authentication. The default implementation simply returns the <code>maximumSessions</code> value
|
||||
* for the bean.
|
||||
*
|
||||
* @param authentication to determine the maximum sessions for
|
||||
*
|
||||
* @return either -1 meaning unlimited, or a positive integer to limit (never zero)
|
||||
*/
|
||||
protected int getMaximumSessionsForThisUser(Authentication authentication) {
|
||||
return maximumSessions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows subclasses to customise behaviour when too many sessions are detected.
|
||||
*
|
||||
* @param sessions either <code>null</code> or all unexpired sessions associated with the principal
|
||||
* @param allowableSessions the number of concurrent sessions the user is allowed to have
|
||||
* @param registry an instance of the <code>SessionRegistry</code> for subclass use
|
||||
*
|
||||
*/
|
||||
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions,
|
||||
SessionRegistry registry) throws SessionAuthenticationException {
|
||||
if (exceptionIfMaximumExceeded || (sessions == null)) {
|
||||
throw new SessionAuthenticationException(messages.getMessage("ConcurrentSessionControlStrategy.exceededAllowed",
|
||||
new Object[] {Integer.valueOf(allowableSessions)},
|
||||
"Maximum sessions of {0} for this principal exceeded"));
|
||||
}
|
||||
|
||||
// Determine least recently used session, and mark it for invalidation
|
||||
SessionInformation leastRecentlyUsed = null;
|
||||
|
||||
for (SessionInformation session : sessions) {
|
||||
if ((leastRecentlyUsed == null)
|
||||
|| session.getLastRequest().before(leastRecentlyUsed.getLastRequest())) {
|
||||
leastRecentlyUsed = session;
|
||||
}
|
||||
}
|
||||
|
||||
leastRecentlyUsed.expireNow();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the <tt>exceptionIfMaximumExceeded</tt> property, which determines whether the user should be prevented
|
||||
* from opening more sessions than allowed. If set to <tt>true</tt>, a <tt>SessionAuthenticationException</tt>
|
||||
* will be raised.
|
||||
*
|
||||
* @param exceptionIfMaximumExceeded defaults to <tt>false</tt>.
|
||||
*/
|
||||
public void setExceptionIfMaximumExceeded(boolean exceptionIfMaximumExceeded) {
|
||||
this.exceptionIfMaximumExceeded = exceptionIfMaximumExceeded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the <tt>maxSessions</tt> property. The default value is 1. Use -1 for unlimited sessions.
|
||||
*
|
||||
* @param maximumSessions the maximimum number of permitted sessions a user can have open simultaneously.
|
||||
*/
|
||||
public void setMaximumSessions(int maximumSessions) {
|
||||
Assert.isTrue(maximumSessions != 0,
|
||||
"MaximumLogins must be either -1 to allow unlimited logins, or a positive integer to specify a maximum");
|
||||
this.maximumSessions = maximumSessions;
|
||||
}
|
||||
|
||||
public void setMessageSource(MessageSource messageSource) {
|
||||
this.messages = new MessageSourceAccessor(messageSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void setAlwaysCreateSession(boolean alwaysCreateSession) {
|
||||
if (!alwaysCreateSession) {
|
||||
throw new IllegalArgumentException("Cannot set alwaysCreateSession to false when concurrent session " +
|
||||
"control is required");
|
||||
}
|
||||
}
|
||||
}
|
||||
-10
@@ -159,14 +159,4 @@ public class SessionFixationProtectionStrategy extends AbstractSessionFixationPr
|
||||
public void setMigrateSessionAttributes(boolean migrateSessionAttributes) {
|
||||
this.migrateSessionAttributes = migrateSessionAttributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Override the {@code extractAttributes} method instead
|
||||
*/
|
||||
@Deprecated
|
||||
public void setRetainedAttributes(List<String> retainedAttributes) {
|
||||
logger.warn("Retained attributes is deprecated. Override the extractAttributes() method instead.");
|
||||
Assert.notNull(retainedAttributes);
|
||||
this.retainedAttributes = retainedAttributes;
|
||||
}
|
||||
}
|
||||
|
||||
-2
@@ -63,7 +63,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {
|
||||
this.failureUrl = DEFAULT_LOGIN_PAGE_URL + "?" + ERROR_PARAMETER_NAME;
|
||||
if (authFilter != null) {
|
||||
formLoginEnabled = true;
|
||||
authenticationUrl = authFilter.getFilterProcessesUrl();
|
||||
usernameParameter = authFilter.getUsernameParameter();
|
||||
passwordParameter = authFilter.getPasswordParameter();
|
||||
|
||||
@@ -74,7 +73,6 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {
|
||||
|
||||
if (openIDFilter != null) {
|
||||
openIdEnabled = true;
|
||||
openIDauthenticationUrl = openIDFilter.getFilterProcessesUrl();
|
||||
openIDusernameParameter = "openid_identifier";
|
||||
|
||||
if (openIDFilter.getRememberMeServices() instanceof AbstractRememberMeServices) {
|
||||
|
||||
+3
-31
@@ -97,12 +97,6 @@ public class BasicAuthenticationFilter extends OncePerRequestFilter {
|
||||
private boolean ignoreFailure = false;
|
||||
private String credentialsCharset = "UTF-8";
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
public BasicAuthenticationFilter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance which will authenticate against the supplied {@code AuthenticationManager}
|
||||
* and which will ignore failed authentication attempts, allowing the request to proceed down the filter chain.
|
||||
@@ -110,6 +104,7 @@ public class BasicAuthenticationFilter extends OncePerRequestFilter {
|
||||
* @param authenticationManager the bean to submit authentication requests to
|
||||
*/
|
||||
public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
|
||||
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
|
||||
this.authenticationManager = authenticationManager;
|
||||
ignoreFailure = true;
|
||||
}
|
||||
@@ -124,6 +119,8 @@ public class BasicAuthenticationFilter extends OncePerRequestFilter {
|
||||
*/
|
||||
public BasicAuthenticationFilter(AuthenticationManager authenticationManager,
|
||||
AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
|
||||
Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null");
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.authenticationEntryPoint = authenticationEntryPoint;
|
||||
}
|
||||
@@ -269,39 +266,14 @@ public class BasicAuthenticationFilter extends OncePerRequestFilter {
|
||||
return authenticationEntryPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
|
||||
this.authenticationEntryPoint = authenticationEntryPoint;
|
||||
}
|
||||
|
||||
protected AuthenticationManager getAuthenticationManager() {
|
||||
return authenticationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
protected boolean isIgnoreFailure() {
|
||||
return ignoreFailure;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @deprecated Use the constructor which takes a single AuthenticationManager parameter
|
||||
*/
|
||||
@Deprecated
|
||||
public void setIgnoreFailure(boolean ignoreFailure) {
|
||||
this.ignoreFailure = ignoreFailure;
|
||||
}
|
||||
|
||||
public void setAuthenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource) {
|
||||
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
|
||||
this.authenticationDetailsSource = authenticationDetailsSource;
|
||||
|
||||
-9
@@ -99,15 +99,6 @@ public class SecurityContextPersistenceFilter extends GenericFilterBean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setSecurityContextRepository(SecurityContextRepository repo) {
|
||||
Assert.notNull(repo, "SecurityContextRepository cannot be null");
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
public void setForceEagerSessionCreation(boolean forceEagerSessionCreation) {
|
||||
this.forceEagerSessionCreation = forceEagerSessionCreation;
|
||||
}
|
||||
|
||||
-8
@@ -45,12 +45,4 @@ public class RequestCacheAwareFilter extends GenericFilterBean {
|
||||
chain.doFilter(wrappedSavedRequest == null ? request : wrappedSavedRequest, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setRequestCache(RequestCache requestCache) {
|
||||
this.requestCache = requestCache;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-24
@@ -64,18 +64,15 @@ public class ConcurrentSessionFilter extends GenericFilterBean {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated Use constructor which injects the <tt>SessionRegistry</tt>.
|
||||
*/
|
||||
public ConcurrentSessionFilter() {
|
||||
}
|
||||
|
||||
public ConcurrentSessionFilter(SessionRegistry sessionRegistry) {
|
||||
this(sessionRegistry, null);
|
||||
Assert.notNull(sessionRegistry, "SessionRegistry required");
|
||||
this.sessionRegistry = sessionRegistry;
|
||||
}
|
||||
|
||||
public ConcurrentSessionFilter(SessionRegistry sessionRegistry, String expiredUrl) {
|
||||
Assert.notNull(sessionRegistry, "SessionRegistry required");
|
||||
Assert.isTrue(expiredUrl == null || UrlUtils.isValidRedirectUrl(expiredUrl),
|
||||
expiredUrl + " isn't a valid redirect URL");
|
||||
this.sessionRegistry = sessionRegistry;
|
||||
this.expiredUrl = expiredUrl;
|
||||
}
|
||||
@@ -137,22 +134,6 @@ public class ConcurrentSessionFilter extends GenericFilterBean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use constructor injection instead
|
||||
*/
|
||||
@Deprecated
|
||||
public void setExpiredUrl(String expiredUrl) {
|
||||
this.expiredUrl = expiredUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use constructor injection instead
|
||||
*/
|
||||
@Deprecated
|
||||
public void setSessionRegistry(SessionRegistry sessionRegistry) {
|
||||
this.sessionRegistry = sessionRegistry;
|
||||
}
|
||||
|
||||
public void setLogoutHandlers(LogoutHandler[] handlers) {
|
||||
Assert.notNull(handlers);
|
||||
this.handlers = handlers;
|
||||
|
||||
-13
@@ -103,19 +103,6 @@ public class SessionManagementFilter extends GenericFilterBean {
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the strategy object which handles the session management behaviour when a
|
||||
* user has been authenticated during the current request.
|
||||
*
|
||||
* @param sessionAuthenticationStrategy the strategy object. If not set, a {@link SessionFixationProtectionStrategy} is used.
|
||||
* @deprecated Use constructor injection
|
||||
*/
|
||||
@Deprecated
|
||||
public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthenticationStrategy) {
|
||||
Assert.notNull(sessionAuthenticationStrategy, "authenticatedSessionStrategy must not be null");
|
||||
this.sessionAuthenticationStrategy = sessionAuthenticationStrategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the strategy which will be invoked instead of allowing the filter chain to prceed, if the user agent
|
||||
* requests an invalid session Id. If the property is not set, no action will be taken.
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
/*
|
||||
* 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.security.web.util;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Matcher which compares a pre-defined ant-style pattern against the URL
|
||||
* ({@code servletPath + pathInfo}) of an {@code HttpServletRequest}.
|
||||
* The query string of the URL is ignored and matching is case-insensitive or case-sensitive depending on
|
||||
* the arguments passed into the constructor.
|
||||
* <p>
|
||||
* Using a pattern value of {@code /**} or {@code **} is treated as a universal
|
||||
* match, which will match any request. Patterns which end with {@code /**} (and have no other wildcards)
|
||||
* are optimized by using a substring match — a pattern of {@code /aaa/**} will match {@code /aaa},
|
||||
* {@code /aaa/} and any sub-directories, such as {@code /aaa/bbb/ccc}.
|
||||
* </p>
|
||||
* <p>
|
||||
* For all other cases, Spring's {@link AntPathMatcher} is used to perform the match. See the Spring documentation
|
||||
* for this class for comprehensive information on the syntax used.
|
||||
* </p>
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @since 3.1
|
||||
* @deprecated use {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
|
||||
* @see org.springframework.util.AntPathMatcher
|
||||
*/
|
||||
public final class AntPathRequestMatcher implements RequestMatcher {
|
||||
private static final Log logger = LogFactory.getLog(AntPathRequestMatcher.class);
|
||||
private static final String MATCH_ALL = "/**";
|
||||
|
||||
private final Matcher matcher;
|
||||
private final String pattern;
|
||||
private final HttpMethod httpMethod;
|
||||
private final boolean caseSensitive;
|
||||
|
||||
/**
|
||||
* Creates a matcher with the specific pattern which will match all HTTP
|
||||
* methods in a case insensitive manner.
|
||||
*
|
||||
* @param pattern
|
||||
* the ant pattern to use for matching
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern) {
|
||||
this(pattern, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the supplied pattern and HTTP method in a case
|
||||
* insensitive manner.
|
||||
*
|
||||
* @param pattern
|
||||
* the ant pattern to use for matching
|
||||
* @param httpMethod
|
||||
* the HTTP method. The {@code matches} method will return false
|
||||
* if the incoming request doesn't have the same method.
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern, String httpMethod) {
|
||||
this(pattern,httpMethod,false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher with the supplied pattern which will match the
|
||||
* specified Http method
|
||||
*
|
||||
* @param pattern
|
||||
* the ant pattern to use for matching
|
||||
* @param httpMethod
|
||||
* the HTTP method. The {@code matches} method will return false
|
||||
* if the incoming request doesn't doesn't have the same method.
|
||||
* @param caseSensitive
|
||||
* true if the matcher should consider case, else false
|
||||
*/
|
||||
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive) {
|
||||
Assert.hasText(pattern, "Pattern cannot be null or empty");
|
||||
this.caseSensitive = caseSensitive;
|
||||
|
||||
if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
|
||||
pattern = MATCH_ALL;
|
||||
matcher = null;
|
||||
} else {
|
||||
if(!caseSensitive) {
|
||||
pattern = pattern.toLowerCase();
|
||||
}
|
||||
|
||||
// If the pattern ends with {@code /**} and has no other wildcards, then optimize to a sub-path match
|
||||
if (pattern.endsWith(MATCH_ALL) && pattern.indexOf('?') == -1 &&
|
||||
pattern.indexOf("*") == pattern.length() - 2) {
|
||||
matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3));
|
||||
} else {
|
||||
matcher = new SpringAntMatcher(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
this.pattern = pattern;
|
||||
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the configured pattern (and HTTP-Method) match those of the supplied request.
|
||||
*
|
||||
* @param request the request to match against. The ant pattern will be matched against the
|
||||
* {@code servletPath} + {@code pathInfo} of the request.
|
||||
*/
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
if (httpMethod != null && request.getMethod() != null && httpMethod != HttpMethod.valueOf(request.getMethod())) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request '" + request.getMethod() + " " + getRequestPath(request) + "'"
|
||||
+ " doesn't match '" + httpMethod + " " + pattern);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (pattern.equals(MATCH_ALL)) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request '" + getRequestPath(request) + "' matched by universal pattern '/**'");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
String url = getRequestPath(request);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Checking match of request : '" + url + "'; against '" + pattern + "'");
|
||||
}
|
||||
|
||||
return matcher.matches(url);
|
||||
}
|
||||
|
||||
private String getRequestPath(HttpServletRequest request) {
|
||||
String url = request.getServletPath();
|
||||
|
||||
if (request.getPathInfo() != null) {
|
||||
url += request.getPathInfo();
|
||||
}
|
||||
|
||||
if(!caseSensitive) {
|
||||
url = url.toLowerCase();
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
public String getPattern() {
|
||||
return pattern;
|
||||
}
|
||||
|
||||
public HttpMethod getHttpMethod() {
|
||||
return httpMethod;
|
||||
}
|
||||
|
||||
public boolean isCaseSensitive() {
|
||||
return caseSensitive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof AntPathRequestMatcher)) {
|
||||
return false;
|
||||
}
|
||||
AntPathRequestMatcher other = (AntPathRequestMatcher)obj;
|
||||
return this.pattern.equals(other.pattern) &&
|
||||
this.httpMethod == other.httpMethod &&
|
||||
this.caseSensitive == other.caseSensitive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int code = 31 ^ pattern.hashCode();
|
||||
if (httpMethod != null) {
|
||||
code ^= httpMethod.hashCode();
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Ant [pattern='").append(pattern).append("'");
|
||||
|
||||
if (httpMethod != null) {
|
||||
sb.append(", ").append(httpMethod);
|
||||
}
|
||||
|
||||
sb.append("]");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static interface Matcher {
|
||||
boolean matches(String path);
|
||||
}
|
||||
|
||||
private static class SpringAntMatcher implements Matcher {
|
||||
private static final AntPathMatcher antMatcher = new AntPathMatcher();
|
||||
|
||||
private final String pattern;
|
||||
|
||||
private SpringAntMatcher(String pattern) {
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
public boolean matches(String path) {
|
||||
return antMatcher.match(pattern, path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimized matcher for trailing wildcards
|
||||
*/
|
||||
private static class SubpathMatcher implements Matcher {
|
||||
private final String subpath;
|
||||
private final int length;
|
||||
|
||||
private SubpathMatcher(String subpath) {
|
||||
assert !subpath.contains("*");
|
||||
this.subpath = subpath;
|
||||
this.length = subpath.length();
|
||||
}
|
||||
|
||||
public boolean matches(String path) {
|
||||
return path.startsWith(subpath) && (path.length() == length || path.charAt(length) == '/');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package org.springframework.security.web.util;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* Matches any supplied request.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @since 3.1
|
||||
* @deprecated use org.springframework.security.web.util.matcher.AnyRequestMatcher.INSTANCE instead
|
||||
*/
|
||||
public final class AnyRequestMatcher implements RequestMatcher {
|
||||
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj instanceof AnyRequestMatcher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 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.security.web.util;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
|
||||
|
||||
/**
|
||||
* A RequestMatcher implementation which uses a SpEL expression
|
||||
*
|
||||
* <p>With the default EvaluationContext ({@link ELRequestMatcherContext}) you can use
|
||||
* <code>hasIpAdress()</code> and <code>hasHeader()</code></p>
|
||||
*
|
||||
* <p>See {@link DelegatingAuthenticationEntryPoint} for an example configuration.</p>
|
||||
*
|
||||
*
|
||||
* @author Mike Wiesner
|
||||
* @since 3.0.2
|
||||
* @deprecated Use org.springframework.security.web.util.matcher.ELRequestMatcher
|
||||
*/
|
||||
public class ELRequestMatcher implements RequestMatcher {
|
||||
|
||||
private final Expression expression;
|
||||
|
||||
public ELRequestMatcher(String el) {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
expression = parser.parseExpression(el);
|
||||
}
|
||||
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
EvaluationContext context = createELContext(request);
|
||||
return expression.getValue(context, Boolean.class).booleanValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this methode if they want to use a different EL root context
|
||||
*
|
||||
* @return EL root context which is used to evaluate the expression
|
||||
*/
|
||||
public EvaluationContext createELContext(HttpServletRequest request) {
|
||||
return new StandardEvaluationContext(new ELRequestMatcherContext(request));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright 2009 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.security.web.util;
|
||||
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
class ELRequestMatcherContext {
|
||||
|
||||
private final HttpServletRequest request;
|
||||
|
||||
public ELRequestMatcherContext(HttpServletRequest request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public boolean hasIpAddress(String ipAddress) {
|
||||
return (new IpAddressMatcher(ipAddress).matches(request));
|
||||
}
|
||||
|
||||
public boolean hasHeader(String headerName, String value) {
|
||||
String header = request.getHeader(headerName);
|
||||
if (!StringUtils.hasText(header)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (header.contains(value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package org.springframework.security.web.util;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Matches a request based on IP Address or subnet mask matching against the remote address.
|
||||
* <p>
|
||||
* Both IPv6 and IPv4 addresses are supported, but a matcher which is configured with an IPv4 address will
|
||||
* never match a request which returns an IPv6 address, and vice-versa.
|
||||
*
|
||||
* @deprecated use {@link org.springframework.security.web.util.matcher.IpAddressMatcher}
|
||||
* @author Luke Taylor
|
||||
* @since 3.0.2
|
||||
*/
|
||||
public final class IpAddressMatcher implements RequestMatcher {
|
||||
private final int nMaskBits;
|
||||
private final InetAddress requiredAddress;
|
||||
|
||||
/**
|
||||
* Takes a specific IP address or a range specified using the
|
||||
* IP/Netmask (e.g. 192.168.1.0/24 or 202.24.0.0/14).
|
||||
*
|
||||
* @param ipAddress the address or range of addresses from which the request must come.
|
||||
*/
|
||||
public IpAddressMatcher(String ipAddress) {
|
||||
|
||||
if (ipAddress.indexOf('/') > 0) {
|
||||
String[] addressAndMask = StringUtils.split(ipAddress, "/");
|
||||
ipAddress = addressAndMask[0];
|
||||
nMaskBits = Integer.parseInt(addressAndMask[1]);
|
||||
} else {
|
||||
nMaskBits = -1;
|
||||
}
|
||||
requiredAddress = parseAddress(ipAddress);
|
||||
}
|
||||
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
return matches(request.getRemoteAddr());
|
||||
}
|
||||
|
||||
public boolean matches(String address) {
|
||||
InetAddress remoteAddress = parseAddress(address);
|
||||
|
||||
if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (nMaskBits < 0) {
|
||||
return remoteAddress.equals(requiredAddress);
|
||||
}
|
||||
|
||||
byte[] remAddr = remoteAddress.getAddress();
|
||||
byte[] reqAddr = requiredAddress.getAddress();
|
||||
|
||||
int oddBits = nMaskBits % 8;
|
||||
int nMaskBytes = nMaskBits/8 + (oddBits == 0 ? 0 : 1);
|
||||
byte[] mask = new byte[nMaskBytes];
|
||||
|
||||
Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte)0xFF);
|
||||
|
||||
if (oddBits != 0) {
|
||||
int finalByte = (1 << oddBits) - 1;
|
||||
finalByte <<= 8-oddBits;
|
||||
mask[mask.length - 1] = (byte) finalByte;
|
||||
}
|
||||
|
||||
// System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));
|
||||
|
||||
for (int i=0; i < mask.length; i++) {
|
||||
if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private InetAddress parseAddress(String address) {
|
||||
try {
|
||||
return InetAddress.getByName(address);
|
||||
} catch (UnknownHostException e) {
|
||||
throw new IllegalArgumentException("Failed to parse address" + address, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
* 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.security.web.util;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Uses a regular expression to decide whether a supplied the URL of a supplied {@code HttpServletRequest}.
|
||||
*
|
||||
* Can also be configured to match a specific HTTP method.
|
||||
*
|
||||
* The match is performed against the {@code servletPath + pathInfo + queryString} of the request and is case-sensitive
|
||||
* by default. Case-insensitive matching can be used by using the constructor which takes the {@code caseInsensitive}
|
||||
* argument.
|
||||
*
|
||||
* @deprecated use {@link org.springframework.security.web.util.matcher.RegexRequestMatcher}
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @author Rob Winch
|
||||
* @since 3.1
|
||||
*/
|
||||
public final class RegexRequestMatcher implements RequestMatcher {
|
||||
private final static Log logger = LogFactory.getLog(RegexRequestMatcher.class);
|
||||
|
||||
private final Pattern pattern;
|
||||
private final HttpMethod httpMethod;
|
||||
|
||||
/**
|
||||
* Creates a case-sensitive {@code Pattern} instance to match against the request.
|
||||
*
|
||||
* @param pattern the regular expression to compile into a pattern.
|
||||
* @param httpMethod the HTTP method to match. May be null to match all methods.
|
||||
*/
|
||||
public RegexRequestMatcher(String pattern, String httpMethod) {
|
||||
this(pattern, httpMethod, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, but allows setting of whether case-insensitive matching should be used.
|
||||
*
|
||||
* @param pattern the regular expression to compile into a pattern.
|
||||
* @param httpMethod the HTTP method to match. May be null to match all methods.
|
||||
* @param caseInsensitive if true, the pattern will be compiled with the {@link Pattern#CASE_INSENSITIVE} flag set.
|
||||
*/
|
||||
public RegexRequestMatcher(String pattern, String httpMethod, boolean caseInsensitive) {
|
||||
if (caseInsensitive) {
|
||||
this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
|
||||
} else {
|
||||
this.pattern = Pattern.compile(pattern);
|
||||
}
|
||||
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the match of the request URL ({@code servletPath + pathInfo + queryString}) against
|
||||
* the compiled pattern. If the query string is present, a question mark will be prepended.
|
||||
*
|
||||
* @param request the request to match
|
||||
* @return true if the pattern matches the URL, false otherwise.
|
||||
*/
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
if (httpMethod != null && request.getMethod() != null && httpMethod != HttpMethod.valueOf(request.getMethod())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String url = request.getServletPath();
|
||||
String pathInfo = request.getPathInfo();
|
||||
String query = request.getQueryString();
|
||||
|
||||
if (pathInfo != null || query != null) {
|
||||
StringBuilder sb = new StringBuilder(url);
|
||||
|
||||
if (pathInfo != null) {
|
||||
sb.append(pathInfo);
|
||||
}
|
||||
|
||||
if (query != null) {
|
||||
sb.append('?').append(query);
|
||||
}
|
||||
url = sb.toString();
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Checking match of request : '" + url + "'; against '" + pattern + "'");
|
||||
}
|
||||
|
||||
return pattern.matcher(url).matches();
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.springframework.security.web.util;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* Simple strategy to match an <tt>HttpServletRequest</tt>.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @since 3.0.2
|
||||
* @deprecated use {@link org.springframework.security.web.util.matcher.RequestMatcher}
|
||||
*/
|
||||
public interface RequestMatcher extends org.springframework.security.web.util.matcher.RequestMatcher {
|
||||
|
||||
/**
|
||||
* Decides whether the rule implemented by the strategy matches the supplied request.
|
||||
*
|
||||
* @param request the request to check for a match
|
||||
* @return true if the request matches, false otherwise
|
||||
*/
|
||||
boolean matches(HttpServletRequest request);
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 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.security.web.util;
|
||||
|
||||
import java.beans.PropertyEditorSupport;
|
||||
|
||||
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
|
||||
|
||||
/**
|
||||
* PropertyEditor which creates ELRequestMatcher instances from Strings
|
||||
*
|
||||
* This allows to use a String in a BeanDefinition instead of an (inner) bean
|
||||
* if a RequestMatcher is required, e.g. in {@link DelegatingAuthenticationEntryPoint}
|
||||
*
|
||||
* @author Mike Wiesner
|
||||
* @since 3.0.2
|
||||
* @deprecated use {@link org.springframework.security.web.util.matcher.RequestMatcherEditor}
|
||||
*/
|
||||
public class RequestMatcherEditor extends PropertyEditorSupport {
|
||||
|
||||
@Override
|
||||
public void setAsText(String text) throws IllegalArgumentException {
|
||||
setValue(new ELRequestMatcher(text));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -81,15 +81,6 @@ public class FilterChainProxyTests {
|
||||
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Deprecated
|
||||
public void filterChainMapIsCorrect() throws Exception {
|
||||
fcp.setFilterChainMap(fcp.getFilterChainMap());
|
||||
Map<RequestMatcher, List<Filter>> filterChainMap = fcp.getFilterChainMap();
|
||||
assertEquals(1, filterChainMap.size());
|
||||
assertSame(filter, filterChainMap.get(matcher).get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
|
||||
+8
-21
@@ -93,8 +93,7 @@ public class ExceptionTranslationFilterTests {
|
||||
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
|
||||
assertNotNull(filter.getAuthenticationTrustResolver());
|
||||
|
||||
@@ -123,8 +122,7 @@ public class ExceptionTranslationFilterTests {
|
||||
adh.setErrorPage("/error.jsp");
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.setAccessDeniedHandler(adh);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@@ -149,8 +147,7 @@ public class ExceptionTranslationFilterTests {
|
||||
doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
@@ -175,11 +172,9 @@ public class ExceptionTranslationFilterTests {
|
||||
doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint, requestCache);
|
||||
requestCache.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
filter.setRequestCache(requestCache);
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
@@ -189,18 +184,12 @@ public class ExceptionTranslationFilterTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void startupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setThrowableAnalyzer(mock(ThrowableAnalyzer.class));
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
new ExceptionTranslationFilter(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void startupDetectsMissingRequestCache() throws Exception {
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
|
||||
filter.setRequestCache(null);
|
||||
new ExceptionTranslationFilter(mockEntryPoint, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -210,8 +199,7 @@ public class ExceptionTranslationFilterTests {
|
||||
request.setServletPath("/secure/page.html");
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
assertSame(mockEntryPoint, filter.getAuthenticationEntryPoint());
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@@ -220,9 +208,8 @@ public class ExceptionTranslationFilterTests {
|
||||
|
||||
@Test
|
||||
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
|
||||
filter.setAuthenticationEntryPoint(mockEntryPoint);
|
||||
filter.afterPropertiesSet();
|
||||
Exception[] exceptions = {new IOException(), new ServletException(), new RuntimeException()};
|
||||
for (Exception e : exceptions) {
|
||||
|
||||
+30
-20
@@ -15,8 +15,26 @@
|
||||
|
||||
package org.springframework.security.web.authentication;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.junit.After;
|
||||
@@ -33,19 +51,12 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServicesTests;
|
||||
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||
import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AbstractAuthenticationProcessingFilter}.
|
||||
@@ -94,8 +105,12 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter();
|
||||
filter.setFilterProcessesUrl("/j_spring_security_check");
|
||||
|
||||
request.setRequestURI("/mycontext/j_spring_security_check;jsessionid=I8MIONOSTHOR");
|
||||
assertTrue(filter.requiresAuthentication(request, response));
|
||||
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
|
||||
request.setServletPath("/j_spring_security_check;jsessionid=I8MIONOSTHOR");
|
||||
|
||||
// the firewall ensures that path parameters are ignored
|
||||
HttpServletRequest firewallRequest = firewall.getFirewalledRequest(request);
|
||||
assertTrue(filter.requiresAuthentication(firewallRequest, response));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,10 +147,9 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
assertNotNull(filter.getRememberMeServices());
|
||||
filter.setRememberMeServices(new TokenBasedRememberMeServices());
|
||||
filter.setRememberMeServices(new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService()));
|
||||
assertEquals(TokenBasedRememberMeServices.class, filter.getRememberMeServices().getClass());
|
||||
assertTrue(filter.getAuthenticationManager() != null);
|
||||
assertEquals("/p", filter.getFilterProcessesUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -218,7 +232,7 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
filter.setFilterProcessesUrl(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("filterProcessesUrl must be specified", expected.getMessage());
|
||||
assertEquals("Pattern cannot be null or empty", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -402,10 +416,6 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
throw exceptionToThrow;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
|
||||
return super.requiresAuthentication(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
private class MockFilterChain implements FilterChain {
|
||||
|
||||
+3
-19
@@ -24,9 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.memory.UserAttribute;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
@@ -59,20 +57,12 @@ public class AnonymousAuthenticationFilterTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingKey() throws Exception {
|
||||
UserAttribute user = new UserAttribute();
|
||||
user.setPassword("anonymousUsername");
|
||||
user.addAuthority(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
|
||||
|
||||
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter();
|
||||
filter.setUserAttribute(user);
|
||||
filter.afterPropertiesSet();
|
||||
new AnonymousAuthenticationFilter(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsUserAttribute() throws Exception {
|
||||
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter();
|
||||
filter.setKey("qwerty");
|
||||
filter.afterPropertiesSet();
|
||||
new AnonymousAuthenticationFilter("qwerty", null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,13 +86,7 @@ public class AnonymousAuthenticationFilterTests {
|
||||
|
||||
@Test
|
||||
public void testOperationWhenNoAuthenticationInSecurityContextHolder() throws Exception {
|
||||
UserAttribute user = new UserAttribute();
|
||||
user.setPassword("anonymousUsername");
|
||||
user.addAuthority(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
|
||||
|
||||
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter();
|
||||
filter.setKey("qwerty");
|
||||
filter.setUserAttribute(user);
|
||||
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
-1
@@ -67,7 +67,6 @@ public class DefaultLoginPageGeneratingFilterTests {
|
||||
MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
String message = messages.getMessage(
|
||||
"AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials", Locale.KOREA);
|
||||
System.out.println("Message: " + message);
|
||||
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(message));
|
||||
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
|
||||
+13
-32
@@ -37,34 +37,24 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingLoginFormUrl() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
new LoginUrlAuthenticationEntryPoint(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("xxx");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login");
|
||||
ep.setPortMapper(null);
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("xxx");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login");
|
||||
ep.setPortResolver(null);
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
assertEquals("/hello", ep.getLoginFormUrl());
|
||||
@@ -91,8 +81,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
@@ -120,8 +109,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
portMapper.setPortMappings(map);
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(portMapper);
|
||||
@@ -143,8 +131,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
@@ -163,8 +150,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
@@ -185,8 +171,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
@Test
|
||||
public void testOperationWhenHttpsRequestsButHttpsPortUnknown() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortResolver(new MockPortResolver(8888, 1234));
|
||||
ep.setForceHttps(true);
|
||||
ep.afterPropertiesSet();
|
||||
@@ -209,8 +194,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
@Test
|
||||
public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setUseForward(true);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -230,8 +214,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
@Test
|
||||
public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
ep.setLoginFormUrl("/hello");
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setUseForward(true);
|
||||
ep.setForceHttps(true);
|
||||
ep.afterPropertiesSet();
|
||||
@@ -253,9 +236,8 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
// SEC-1498
|
||||
@Test
|
||||
public void absoluteLoginFormUrlIsSupported() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
final String loginFormUrl = "http://somesite.com/login";
|
||||
ep.setLoginFormUrl(loginFormUrl);
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(loginFormUrl);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ep.commence(new MockHttpServletRequest("GET", "/someUrl"), response, null);
|
||||
@@ -264,9 +246,8 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void absoluteLoginFormUrlCantBeUsedWithForwarding() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint();
|
||||
final String loginFormUrl = "http://somesite.com/login";
|
||||
ep.setLoginFormUrl(loginFormUrl);
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("http://somesite.com/login");
|
||||
ep.setUseForward(true);
|
||||
ep.afterPropertiesSet();
|
||||
}
|
||||
|
||||
-1
@@ -49,7 +49,6 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
assertEquals("/j_spring_security_check", filter.getFilterProcessesUrl());
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
// filter.init(null);
|
||||
|
||||
|
||||
+8
-2
@@ -6,6 +6,7 @@ import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.web.authentication.logout.LogoutFilter;
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||
import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
@@ -21,9 +22,12 @@ public class LogoutHandlerTests extends TestCase {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setRequestURI("/j_spring_security_logout;someparam=blah?otherparam=blah");
|
||||
request.setRequestURI("/context/j_spring_security_logout;someparam=blah?param=blah");
|
||||
request.setServletPath("/j_spring_security_logout;someparam=blah");
|
||||
request.setQueryString("otherparam=blah");
|
||||
|
||||
assertTrue(filter.requiresLogout(request, response));
|
||||
DefaultHttpFirewall fw = new DefaultHttpFirewall();
|
||||
assertTrue(filter.requiresLogout(fw.getFirewalledRequest(request), response));
|
||||
}
|
||||
|
||||
public void testRequiresLogoutUrlWorksWithQueryParams() {
|
||||
@@ -31,7 +35,9 @@ public class LogoutHandlerTests extends TestCase {
|
||||
request.setContextPath("/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setServletPath("/j_spring_security_logout");
|
||||
request.setRequestURI("/context/j_spring_security_logout?param=blah");
|
||||
request.setQueryString("otherparam=blah");
|
||||
|
||||
assertTrue(filter.requiresLogout(request, response));
|
||||
}
|
||||
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package org.springframework.security.web.authentication.preauth.websphere;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.authentication.AuthenticationDetailsSource;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsChecker;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @since 3.0
|
||||
*/
|
||||
public class WebSphere2SpringSecurityPropagationInterceptorTests {
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
/** SEC-1078 */
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void createdAuthenticationTokenIsAcceptableToPreauthProvider () throws Throwable {
|
||||
WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class);
|
||||
when(helper.getCurrentUserName()).thenReturn("joe");
|
||||
WebSphere2SpringSecurityPropagationInterceptor interceptor =
|
||||
new WebSphere2SpringSecurityPropagationInterceptor(helper);
|
||||
|
||||
final SecurityContext context = new SecurityContextImpl();
|
||||
|
||||
interceptor.setAuthenticationManager(new AuthenticationManager() {
|
||||
public Authentication authenticate(Authentication authentication) {
|
||||
// Store the auth object
|
||||
context.setAuthentication(authentication);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
interceptor.setAuthenticationDetailsSource(mock(AuthenticationDetailsSource.class));
|
||||
interceptor.invoke(mock(MethodInvocation.class));
|
||||
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
AuthenticationUserDetailsService uds = mock(AuthenticationUserDetailsService.class);
|
||||
UserDetails user = mock(UserDetails.class);
|
||||
List authorities = AuthorityUtils.createAuthorityList("SOME_ROLE");
|
||||
when(user.getAuthorities()).thenReturn(authorities);
|
||||
when(uds.loadUserDetails(any(Authentication.class))).thenReturn(user);
|
||||
provider.setPreAuthenticatedUserDetailsService(uds);
|
||||
provider.setUserDetailsChecker(mock(UserDetailsChecker.class));
|
||||
|
||||
assertNotNull(provider.authenticate(context.getAuthentication()));
|
||||
}
|
||||
|
||||
}
|
||||
+49
-36
@@ -13,8 +13,10 @@ import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
@@ -42,17 +44,23 @@ import org.springframework.util.StringUtils;
|
||||
public class AbstractRememberMeServicesTests {
|
||||
static User joe = new User("joe", "password", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
|
||||
MockUserDetailsService uds;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
uds = new MockUserDetailsService(joe, false);
|
||||
}
|
||||
|
||||
@Test(expected = InvalidCookieException.class)
|
||||
public void nonBase64CookieShouldBeDetected() {
|
||||
new MockRememberMeServices().decodeCookie("nonBase64CookieValue%");
|
||||
new MockRememberMeServices(uds).decodeCookie("nonBase64CookieValue%");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAndGetAreConsistent() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertNotNull(services.getCookieName());
|
||||
assertNotNull(services.getParameter());
|
||||
services.setKey("xxxx");
|
||||
assertEquals("xxxx", services.getKey());
|
||||
services.setParameter("rm");
|
||||
assertEquals("rm", services.getParameter());
|
||||
@@ -60,8 +68,6 @@ public class AbstractRememberMeServicesTests {
|
||||
assertEquals("kookie", services.getCookieName());
|
||||
services.setTokenValiditySeconds(600);
|
||||
assertEquals(600, services.getTokenValiditySeconds());
|
||||
UserDetailsService uds = mock(UserDetailsService.class);
|
||||
services.setUserDetailsService(uds);
|
||||
assertSame(uds, services.getUserDetailsService());
|
||||
AuthenticationDetailsSource ads = mock(AuthenticationDetailsSource.class);
|
||||
services.setAuthenticationDetailsSource(ads);
|
||||
@@ -72,7 +78,7 @@ public class AbstractRememberMeServicesTests {
|
||||
@Test
|
||||
public void cookieShouldBeCorrectlyEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] {"name", "cookie", "tokens", "blah"};
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String encoded = services.encodeCookie(cookie);
|
||||
// '=' aren't allowed in version 0 cookies.
|
||||
@@ -89,7 +95,7 @@ public class AbstractRememberMeServicesTests {
|
||||
@Test
|
||||
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] {"http://id.openid.zz", "cookie", "tokens", "blah"};
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
|
||||
assertEquals(4, decoded.length);
|
||||
@@ -104,7 +110,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldReturnNullIfNoLoginCookieIsPresented() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
@@ -123,8 +129,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void successfulAutoLoginReturnsExpectedAuthentication() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
services.setUserDetailsService(new MockUserDetailsService(joe, false));
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
services.afterPropertiesSet();
|
||||
assertNotNull(services.getUserDetailsService());
|
||||
|
||||
@@ -140,7 +145,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfCookieIsNotBase64() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
@@ -152,7 +157,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfCookieIsEmpty() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
@@ -164,8 +169,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
// services.setUserDetailsService(new MockUserDetailsService(joe, true));
|
||||
MockRememberMeServices services = new MockRememberMeServices(new MockUserDetailsService(joe, true));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
// Wrong number of tokens
|
||||
@@ -181,8 +185,8 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfUserNotFound() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
services.setUserDetailsService(new MockUserDetailsService(joe, true));
|
||||
uds.setThrowException(true);
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
@@ -197,10 +201,9 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfUserAccountIsLocked() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
services.setUserDetailsChecker(new AccountStatusUserDetailsChecker());
|
||||
User joeLocked = new User("joe", "password",false,true,true,true,joe.getAuthorities());
|
||||
services.setUserDetailsService(new MockUserDetailsService(joeLocked, false));
|
||||
uds.toReturn = new User("joe", "password",false,true,true,true,joe.getAuthorities());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
@@ -215,8 +218,8 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void loginFailShouldCancelCookie() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
services.setUserDetailsService(new MockUserDetailsService(joe, true));
|
||||
uds.setThrowException(true);
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("contextpath");
|
||||
@@ -230,7 +233,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void logoutShouldCancelCookie() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("contextpath");
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
@@ -247,13 +250,12 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test(expected = CookieTheftException.class)
|
||||
public void cookieTheftExceptionShouldBeRethrown() {
|
||||
MockRememberMeServices services = new MockRememberMeServices() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
|
||||
throw new CookieTheftException("Pretending cookie was stolen");
|
||||
}
|
||||
};
|
||||
|
||||
services.setUserDetailsService(new MockUserDetailsService(joe, false));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
@@ -264,25 +266,24 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void loginSuccessCallsOnLoginSuccessCorrectly() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
Authentication auth = new UsernamePasswordAuthenticationToken("joe","password");
|
||||
|
||||
// No parameter set
|
||||
services = new MockRememberMeServices();
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertFalse(services.loginSuccessCalled);
|
||||
|
||||
// Parameter set to true
|
||||
services = new MockRememberMeServices();
|
||||
services = new MockRememberMeServices(uds);
|
||||
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
|
||||
// Different parameter name, set to true
|
||||
services = new MockRememberMeServices();
|
||||
services = new MockRememberMeServices(uds);
|
||||
services.setParameter("my_parameter");
|
||||
request.setParameter("my_parameter", "true");
|
||||
services.loginSuccess(request, response, auth);
|
||||
@@ -290,13 +291,13 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
|
||||
// Parameter set to false
|
||||
services = new MockRememberMeServices();
|
||||
services = new MockRememberMeServices(uds);
|
||||
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "false");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertFalse(services.loginSuccessCalled);
|
||||
|
||||
// alwaysRemember set to true
|
||||
services = new MockRememberMeServices();
|
||||
services = new MockRememberMeServices(uds);
|
||||
services.setAlwaysRemember(true);
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
@@ -307,7 +308,7 @@ public class AbstractRememberMeServicesTests {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
MockRememberMeServices services = new MockRememberMeServices() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
@@ -329,7 +330,7 @@ public class AbstractRememberMeServicesTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
@@ -345,7 +346,7 @@ public class AbstractRememberMeServicesTests {
|
||||
spy(ReflectionUtils.class);
|
||||
when(ReflectionUtils.findMethod(Cookie.class,"setHttpOnly", boolean.class)).thenReturn(null);
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertNull(ReflectionTestUtils.getField(services, "setHttpOnlyMethod"));
|
||||
|
||||
services = new MockRememberMeServices("key",new MockUserDetailsService(joe, false));
|
||||
@@ -353,7 +354,7 @@ public class AbstractRememberMeServicesTests {
|
||||
}
|
||||
|
||||
private Cookie[] createLoginCookie(String cookieToken) {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, ":")));
|
||||
|
||||
@@ -372,11 +373,15 @@ public class AbstractRememberMeServicesTests {
|
||||
boolean loginSuccessCalled;
|
||||
|
||||
MockRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||
super(key,userDetailsService);
|
||||
super(key, userDetailsService);
|
||||
}
|
||||
|
||||
MockRememberMeServices(UserDetailsService userDetailsService) {
|
||||
super("xxxx", userDetailsService);
|
||||
}
|
||||
|
||||
MockRememberMeServices() {
|
||||
setKey("key");
|
||||
this(new MockUserDetailsService(null,false));
|
||||
}
|
||||
|
||||
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
|
||||
@@ -398,6 +403,10 @@ public class AbstractRememberMeServicesTests {
|
||||
private UserDetails toReturn;
|
||||
private boolean throwException;
|
||||
|
||||
public MockUserDetailsService() {
|
||||
this(null, false);
|
||||
}
|
||||
|
||||
public MockUserDetailsService(UserDetails toReturn, boolean throwException) {
|
||||
this.toReturn = toReturn;
|
||||
this.throwException = throwException;
|
||||
@@ -410,5 +419,9 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
public void setThrowException(boolean value) {
|
||||
this.throwException = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+20
-19
@@ -3,6 +3,7 @@ package org.springframework.security.web.authentication.rememberme;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
|
||||
@@ -18,6 +19,7 @@ import org.springframework.security.web.authentication.rememberme.PersistentReme
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
|
||||
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
|
||||
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServicesTests.*;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
@@ -25,6 +27,8 @@ import org.springframework.security.web.authentication.rememberme.RememberMeAuth
|
||||
public class PersistentTokenBasedRememberMeServicesTests {
|
||||
private PersistentTokenBasedRememberMeServices services;
|
||||
|
||||
private MockTokenRepository repo;
|
||||
|
||||
@Before
|
||||
public void setUpData() throws Exception {
|
||||
services = new PersistentTokenBasedRememberMeServices("key",
|
||||
@@ -44,22 +48,15 @@ public class PersistentTokenBasedRememberMeServicesTests {
|
||||
|
||||
@Test(expected = RememberMeAuthenticationException.class)
|
||||
public void loginIsRejectedWhenNoTokenMatchingSeriesIsFound() {
|
||||
services.setTokenRepository(new MockTokenRepository(null));
|
||||
services = create(null);
|
||||
services.processAutoLoginCookie(new String[] {"series", "token"}, new MockHttpServletRequest(),
|
||||
new MockHttpServletResponse());
|
||||
}
|
||||
|
||||
@Test(expected = RememberMeAuthenticationException.class)
|
||||
public void loginIsRejectedWhenTokenIsExpired() {
|
||||
MockTokenRepository repo =
|
||||
new MockTokenRepository(new PersistentRememberMeToken("joe", "series","token", new Date()));
|
||||
services.setTokenRepository(repo);
|
||||
services = create(new PersistentRememberMeToken("joe", "series","token", new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100)));
|
||||
services.setTokenValiditySeconds(1);
|
||||
try {
|
||||
Thread.sleep(1100);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
services.setTokenRepository(repo);
|
||||
|
||||
services.processAutoLoginCookie(new String[] {"series", "token"}, new MockHttpServletRequest(),
|
||||
new MockHttpServletResponse());
|
||||
@@ -67,17 +64,14 @@ public class PersistentTokenBasedRememberMeServicesTests {
|
||||
|
||||
@Test(expected = CookieTheftException.class)
|
||||
public void cookieTheftIsDetectedWhenSeriesAndTokenDontMatch() {
|
||||
PersistentRememberMeToken token = new PersistentRememberMeToken("joe", "series","wrongtoken", new Date());
|
||||
services.setTokenRepository(new MockTokenRepository(token));
|
||||
services = create(new PersistentRememberMeToken("joe", "series","wrongtoken", new Date()));
|
||||
services.processAutoLoginCookie(new String[] {"series", "token"}, new MockHttpServletRequest(),
|
||||
new MockHttpServletResponse());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulAutoLoginCreatesNewTokenAndCookieWithSameSeries() {
|
||||
MockTokenRepository repo =
|
||||
new MockTokenRepository(new PersistentRememberMeToken("joe", "series","token", new Date()));
|
||||
services.setTokenRepository(repo);
|
||||
services = create(new PersistentRememberMeToken("joe", "series","token", new Date()));
|
||||
// 12 => b64 length will be 16
|
||||
services.setTokenLength(12);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@@ -91,9 +85,8 @@ public class PersistentTokenBasedRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void loginSuccessCreatesNewTokenAndCookieWithNewSeries() {
|
||||
services = create(null);
|
||||
services.setAlwaysRemember(true);
|
||||
MockTokenRepository repo = new MockTokenRepository(null);
|
||||
services.setTokenRepository(repo);
|
||||
services.setTokenLength(12);
|
||||
services.setSeriesLength(12);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@@ -114,9 +107,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockTokenRepository repo =
|
||||
new MockTokenRepository(new PersistentRememberMeToken("joe", "series","token", new Date()));
|
||||
services.setTokenRepository(repo);
|
||||
services = create(new PersistentRememberMeToken("joe", "series","token", new Date()));
|
||||
services.logout(request, response, new TestingAuthenticationToken("joe","somepass","SOME_AUTH"));
|
||||
Cookie returnedCookie = response.getCookie("mycookiename");
|
||||
assertNotNull(returnedCookie);
|
||||
@@ -126,6 +117,16 @@ public class PersistentTokenBasedRememberMeServicesTests {
|
||||
services.logout(request, response, null);
|
||||
}
|
||||
|
||||
private PersistentTokenBasedRememberMeServices create(PersistentRememberMeToken token) {
|
||||
repo = new MockTokenRepository(token);
|
||||
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
|
||||
repo);
|
||||
|
||||
services.setCookieName("mycookiename");
|
||||
return services;
|
||||
}
|
||||
|
||||
private class MockTokenRepository implements PersistentTokenRepository {
|
||||
private PersistentRememberMeToken storedToken;
|
||||
|
||||
|
||||
+10
-38
@@ -60,33 +60,12 @@ public class RememberMeAuthenticationFilterTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsAuthenticationManagerProperty() {
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter();
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setRememberMeServices(new NullRememberMeServices());
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
filter.setAuthenticationManager(null);
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
new RememberMeAuthenticationFilter(null, new NullRememberMeServices());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsRememberMeServicesProperty() {
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter();
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
|
||||
// check default is NullRememberMeServices
|
||||
// assertEquals(NullRememberMeServices.class, filter.getRememberMeServices().getClass());
|
||||
|
||||
// check getter/setter
|
||||
filter.setRememberMeServices(new TokenBasedRememberMeServices());
|
||||
assertEquals(TokenBasedRememberMeServices.class, filter.getRememberMeServices().getClass());
|
||||
|
||||
// check detects if made null
|
||||
filter.setRememberMeServices(null);
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,9 +75,7 @@ public class RememberMeAuthenticationFilterTests {
|
||||
SecurityContextHolder.getContext().setAuthentication(originalAuth);
|
||||
|
||||
// Setup our filter correctly
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter();
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setRememberMeServices(new MockRememberMeServices(remembered));
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), new MockRememberMeServices(remembered));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Test
|
||||
@@ -114,12 +91,10 @@ public class RememberMeAuthenticationFilterTests {
|
||||
|
||||
@Test
|
||||
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(remembered)).thenReturn(remembered);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.setRememberMeServices(new MockRememberMeServices(remembered));
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(remembered));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -135,17 +110,16 @@ public class RememberMeAuthenticationFilterTests {
|
||||
@Test
|
||||
public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception {
|
||||
final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter() {
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(remembered)) {
|
||||
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
|
||||
super.onUnsuccessfulAuthentication(request, response, failed);
|
||||
SecurityContextHolder.getContext().setAuthentication(failedAuth);
|
||||
}
|
||||
};
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.setRememberMeServices(new MockRememberMeServices(remembered));
|
||||
filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
@@ -160,11 +134,9 @@ public class RememberMeAuthenticationFilterTests {
|
||||
|
||||
@Test
|
||||
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(remembered)).thenReturn(remembered);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.setRememberMeServices(new MockRememberMeServices(remembered));
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(remembered));
|
||||
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
+3
-6
@@ -53,10 +53,8 @@ public class TokenBasedRememberMeServicesTests {
|
||||
|
||||
@Before
|
||||
public void createTokenBasedRememberMeServices() {
|
||||
services = new TokenBasedRememberMeServices();
|
||||
uds = mock(UserDetailsService.class);
|
||||
services.setKey("key");
|
||||
services.setUserDetailsService(uds);
|
||||
services = new TokenBasedRememberMeServices("key",uds);
|
||||
}
|
||||
|
||||
void udsWillReturnUser() {
|
||||
@@ -227,8 +225,7 @@ public class TokenBasedRememberMeServicesTests {
|
||||
public void testGettersSetters() {
|
||||
assertEquals(uds, services.getUserDetailsService());
|
||||
|
||||
services.setKey("d");
|
||||
assertEquals("d", services.getKey());
|
||||
assertEquals("key", services.getKey());
|
||||
|
||||
assertEquals(DEFAULT_PARAMETER, services.getParameter());
|
||||
services.setParameter("some_param");
|
||||
@@ -251,7 +248,7 @@ public class TokenBasedRememberMeServicesTests {
|
||||
|
||||
@Test
|
||||
public void loginSuccessIgnoredIfParameterNotSetOrFalse() {
|
||||
TokenBasedRememberMeServices services = new TokenBasedRememberMeServices();
|
||||
TokenBasedRememberMeServices services = new TokenBasedRememberMeServices("key",new AbstractRememberMeServicesTests.MockUserDetailsService(null, false));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(DEFAULT_PARAMETER, "false");
|
||||
|
||||
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
* 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.security.web.authentication.session;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.AdditionalMatchers.not;
|
||||
import static org.mockito.Matchers.anyObject;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.session.SessionRegistry;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ConcurrentSessionControlStrategyTests {
|
||||
@Mock
|
||||
private SessionRegistry sessionRegistry;
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private ConcurrentSessionControlStrategy strategy;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
strategy = new ConcurrentSessionControlStrategy(sessionRegistry);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onAuthenticationNewSession() {
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
verify(sessionRegistry,times(0)).removeSessionInformation(anyString());
|
||||
verify(sessionRegistry).registerNewSession(anyString(), anyObject());
|
||||
}
|
||||
|
||||
// SEC-1875
|
||||
@Test
|
||||
public void onAuthenticationChangeSession() {
|
||||
String originalSessionId = request.getSession().getId();
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
verify(sessionRegistry,times(0)).removeSessionInformation(anyString());
|
||||
verify(sessionRegistry).registerNewSession(not(eq(originalSessionId)), anyObject());
|
||||
}
|
||||
|
||||
// SEC-2002
|
||||
@Test
|
||||
public void onAuthenticationChangeSessionWithEventPublisher() {
|
||||
String originalSessionId = request.getSession().getId();
|
||||
|
||||
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
|
||||
strategy.setApplicationEventPublisher(eventPublisher);
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
verify(sessionRegistry,times(0)).removeSessionInformation(anyString());
|
||||
verify(sessionRegistry).registerNewSession(not(eq(originalSessionId)), anyObject());
|
||||
|
||||
ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
|
||||
verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
|
||||
|
||||
assertNotNull(eventArgumentCaptor.getValue());
|
||||
assertTrue(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent);
|
||||
SessionFixationProtectionEvent event = (SessionFixationProtectionEvent)eventArgumentCaptor.getValue();
|
||||
assertEquals(originalSessionId, event.getOldSessionId());
|
||||
assertEquals(request.getSession().getId(), event.getNewSessionId());
|
||||
assertSame(authentication, event.getAuthentication());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void setApplicationEventPublisherForbidsNulls() {
|
||||
strategy.setApplicationEventPublisher(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onAuthenticationNoExceptionWhenRequireApplicationEventPublisherSet() {
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
}
|
||||
}
|
||||
+4
-14
@@ -67,9 +67,7 @@ public class BasicAuthenticationFilterTests {
|
||||
when(manager.authenticate(rodRequest)).thenReturn(rod);
|
||||
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
|
||||
|
||||
filter = new BasicAuthenticationFilter();
|
||||
filter.setAuthenticationManager(manager);
|
||||
filter.setAuthenticationEntryPoint(new BasicAuthenticationEntryPoint());
|
||||
filter = new BasicAuthenticationFilter(manager,new BasicAuthenticationEntryPoint());
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -95,11 +93,7 @@ public class BasicAuthenticationFilterTests {
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
BasicAuthenticationFilter filter = new BasicAuthenticationFilter();
|
||||
filter.setAuthenticationManager(manager);
|
||||
assertThat(filter.getAuthenticationManager()).isNotNull();
|
||||
|
||||
filter.setAuthenticationEntryPoint(mock(AuthenticationEntryPoint.class));
|
||||
assertThat(filter.getAuthenticationEntryPoint()).isNotNull();
|
||||
}
|
||||
|
||||
@@ -168,16 +162,12 @@ public class BasicAuthenticationFilterTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testStartupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
BasicAuthenticationFilter filter = new BasicAuthenticationFilter();
|
||||
filter.setAuthenticationManager(manager);
|
||||
filter.afterPropertiesSet();
|
||||
new BasicAuthenticationFilter(manager, null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testStartupDetectsMissingAuthenticationManager() throws Exception {
|
||||
BasicAuthenticationFilter filter = new BasicAuthenticationFilter();
|
||||
filter.setAuthenticationEntryPoint(mock(AuthenticationEntryPoint.class));
|
||||
filter.afterPropertiesSet();
|
||||
BasicAuthenticationFilter filter = new BasicAuthenticationFilter(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -225,7 +215,7 @@ public class BasicAuthenticationFilterTests {
|
||||
request.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
|
||||
filter.setIgnoreFailure(true);
|
||||
filter = new BasicAuthenticationFilter(manager);
|
||||
assertThat(filter.isIgnoreFailure()).isTrue();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
|
||||
+9
-17
@@ -51,16 +51,14 @@ public class ConcurrentSessionFilterTests {
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test fixture and registry to want this session to be expired
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter();
|
||||
filter.setRedirectStrategy(new DefaultRedirectStrategy());
|
||||
filter.setLogoutHandlers(new LogoutHandler[] {new SecurityContextLogoutHandler()});
|
||||
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
registry.getSessionInformation(session.getId()).expireNow();
|
||||
filter.setSessionRegistry(registry);
|
||||
filter.setExpiredUrl("/expired.jsp");
|
||||
|
||||
// Setup our test fixture and registry to want this session to be expired
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,"/expired.jsp");
|
||||
filter.setRedirectStrategy(new DefaultRedirectStrategy());
|
||||
filter.setLogoutHandlers(new LogoutHandler[]{new SecurityContextLogoutHandler()});
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
@@ -80,11 +78,10 @@ public class ConcurrentSessionFilterTests {
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter();
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
registry.getSessionInformation(session.getId()).expireNow();
|
||||
filter.setSessionRegistry(registry);
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
|
||||
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, fc);
|
||||
@@ -96,15 +93,12 @@ public class ConcurrentSessionFilterTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void detectsMissingSessionRegistry() throws Exception {
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter();
|
||||
filter.afterPropertiesSet();
|
||||
new ConcurrentSessionFilter(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void detectsInvalidUrl() throws Exception {
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter();
|
||||
filter.setExpiredUrl("ImNotValid");
|
||||
filter.afterPropertiesSet();
|
||||
new ConcurrentSessionFilter(new SessionRegistryImpl(), "ImNotValid");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,13 +112,11 @@ public class ConcurrentSessionFilterTests {
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
|
||||
// Setup our test fixture
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter();
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, "/expired.jsp");
|
||||
|
||||
Date lastRequest = registry.getSessionInformation(session.getId()).getLastRequest();
|
||||
filter.setSessionRegistry(registry);
|
||||
filter.setExpiredUrl("/expired.jsp");
|
||||
|
||||
Thread.sleep(1000);
|
||||
|
||||
|
||||
+3
-6
@@ -61,14 +61,13 @@ public class SecurityContextPersistenceFilterTests {
|
||||
public void loadedContextContextIsCopiedToSecurityContextHolderAndUpdatedContextIsStored() throws Exception {
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken("someoneelse", "passwd", "ROLE_B");
|
||||
final SecurityContext scBefore = new SecurityContextImpl();
|
||||
final SecurityContext scExpectedAfter = new SecurityContextImpl();
|
||||
scExpectedAfter.setAuthentication(testToken);
|
||||
scBefore.setAuthentication(beforeAuth);
|
||||
final SecurityContextRepository repo = mock(SecurityContextRepository.class);
|
||||
filter.setSecurityContextRepository(repo);
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
|
||||
|
||||
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
|
||||
|
||||
@@ -90,8 +89,7 @@ public class SecurityContextPersistenceFilterTests {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
filter.setSecurityContextRepository(mock(SecurityContextRepository.class));
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(mock(SecurityContextRepository.class));
|
||||
|
||||
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
|
||||
filter.doFilter(request, response, chain);
|
||||
@@ -114,9 +112,8 @@ public class SecurityContextPersistenceFilterTests {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
SecurityContextRepository repo = new NullSecurityContextRepository();
|
||||
filter.setSecurityContextRepository(repo);
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
|
||||
filter.doFilter(request, response, chain);
|
||||
assertFalse(repo.containsContext(request));
|
||||
assertNull(request.getSession(false));
|
||||
|
||||
+5
-10
@@ -66,8 +66,7 @@ public class SessionManagementFilterTests {
|
||||
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
|
||||
// mock that repo contains a security context
|
||||
when(repo.containsContext(any(HttpServletRequest.class))).thenReturn(true);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo);
|
||||
filter.setSessionAuthenticationStrategy(strategy);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo,strategy);
|
||||
HttpServletRequest request = new MockHttpServletRequest();
|
||||
authenticateUser();
|
||||
|
||||
@@ -80,8 +79,7 @@ public class SessionManagementFilterTests {
|
||||
public void strategyIsNotInvokedIfAuthenticationIsNull() throws Exception {
|
||||
SecurityContextRepository repo = mock(SecurityContextRepository.class);
|
||||
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo);
|
||||
filter.setSessionAuthenticationStrategy(strategy);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo,strategy);
|
||||
HttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
|
||||
@@ -94,8 +92,7 @@ public class SessionManagementFilterTests {
|
||||
SecurityContextRepository repo = mock(SecurityContextRepository.class);
|
||||
// repo will return false to containsContext()
|
||||
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo);
|
||||
filter.setSessionAuthenticationStrategy(strategy);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo,strategy);
|
||||
HttpServletRequest request = new MockHttpServletRequest();
|
||||
authenticateUser();
|
||||
|
||||
@@ -114,9 +111,8 @@ public class SessionManagementFilterTests {
|
||||
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
|
||||
|
||||
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo,strategy);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
filter.setSessionAuthenticationStrategy(strategy);
|
||||
HttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
@@ -135,8 +131,7 @@ public class SessionManagementFilterTests {
|
||||
SecurityContextRepository repo = mock(SecurityContextRepository.class);
|
||||
// repo will return false to containsContext()
|
||||
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo);
|
||||
filter.setSessionAuthenticationStrategy(strategy);
|
||||
SessionManagementFilter filter = new SessionManagementFilter(repo,strategy);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestedSessionId("xxx");
|
||||
request.setRequestedSessionIdValid(false);
|
||||
|
||||
Reference in New Issue
Block a user