Add constructors to facilitate constructor-based injection for required/shared bean properties.

This commit is contained in:
Luke Taylor 2011-07-05 20:25:49 +01:00
parent 73442125de
commit 2d271666a4
20 changed files with 312 additions and 36 deletions

View File

@ -50,6 +50,13 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
private boolean allowIfAllAbstainDecisions = false;
protected AbstractAccessDecisionManager() {
}
protected AbstractAccessDecisionManager(List<AccessDecisionVoter> decisionVoters) {
this.decisionVoters = decisionVoters;
}
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
@ -76,6 +83,10 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
}
/**
* @deprecated Use constructor
*/
@Deprecated
public void setDecisionVoters(List<AccessDecisionVoter> newList) {
Assert.notEmpty(newList);

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.*;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
@ -28,6 +28,18 @@ import org.springframework.security.core.Authentication;
* <code>AccessDecisionVoter</code> returns an affirmative response.
*/
public class AffirmativeBased extends AbstractAccessDecisionManager {
/**
* @deprecated Use constructor which takes voter list
*/
@Deprecated
public AffirmativeBased() {
}
public AffirmativeBased(List<AccessDecisionVoter> decisionVoters) {
super(decisionVoters);
}
//~ Methods ========================================================================================================
/**

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.*;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
@ -34,6 +34,17 @@ public class ConsensusBased extends AbstractAccessDecisionManager {
private boolean allowIfEqualGrantedDeniedDecisions = true;
/**
* @deprecated Use constructor which takes voter list
*/
@Deprecated
public ConsensusBased() {
}
public ConsensusBased(List<AccessDecisionVoter> decisionVoters) {
super(decisionVoters);
}
//~ Methods ========================================================================================================
/**

View File

@ -30,6 +30,18 @@ import org.springframework.security.core.Authentication;
* voters to abstain or grant access.
*/
public class UnanimousBased extends AbstractAccessDecisionManager {
/**
* @deprecated Use constructor which takes voter list
*/
@Deprecated
public UnanimousBased() {
}
public UnanimousBased(List<AccessDecisionVoter> decisionVoters) {
super(decisionVoters);
}
//~ Methods ========================================================================================================
/**

View File

@ -40,11 +40,22 @@ public class AnonymousAuthenticationProvider implements AuthenticationProvider,
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private String key;
/**
*
* @deprecated Use constructor injection
*/
@Deprecated
public AnonymousAuthenticationProvider() {
}
public AnonymousAuthenticationProvider(String key) {
this.key = key;
}
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(key, "A Key is required");
Assert.notNull(this.messages, "A message source must be set");
}
public Authentication authenticate(Authentication authentication)
@ -65,11 +76,17 @@ public class AnonymousAuthenticationProvider implements AuthenticationProvider,
return key;
}
/**
*
* @deprecated Use constructor injection
*/
@Deprecated
public void setKey(String key) {
this.key = key;
}
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}

View File

@ -88,6 +88,22 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar
private boolean eraseCredentialsAfterAuthentication = true;
private boolean clearExtraInformation = false;
/**
* @deprecated Use constructor which takes provider list
*/
@Deprecated
public ProviderManager() {
}
public ProviderManager(List<AuthenticationProvider> providers) {
this(providers, null);
}
public ProviderManager(List<AuthenticationProvider> providers, AuthenticationManager parent) {
this.providers = providers;
this.parent = parent;
}
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
@ -212,6 +228,10 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* @deprecated Use constructor injection
*/
@Deprecated
public void setParent(AuthenticationManager parent) {
this.parent = parent;
}
@ -244,7 +264,9 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar
*
* @throws IllegalArgumentException if the list is empty or null, or any of the elements in the list is not an
* AuthenticationProvider instance.
* @deprecated Use constructor injection
*/
@Deprecated
@SuppressWarnings("unchecked")
public void setProviders(List providers) {
Assert.notNull(providers, "Providers list cannot be null");

View File

@ -37,6 +37,17 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider,
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private String key;
/**
* @deprecated Use constructor injection
*/
@Deprecated
public RememberMeAuthenticationProvider() {
}
public RememberMeAuthenticationProvider(String key) {
this.key = key;
}
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
@ -61,6 +72,11 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider,
return key;
}
/**
*
* @deprecated Use constructor injection
*/
@Deprecated
public void setKey(String key) {
this.key = key;
}

View File

@ -206,23 +206,19 @@ public class ProviderManagerTests {
@Test
public void parentAuthenticationIsUsedIfProvidersDontAuthenticate() throws Exception {
ProviderManager mgr = new ProviderManager();
mgr.setProviders(Arrays.asList(mock(AuthenticationProvider.class)));
Authentication authReq = mock(Authentication.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
Authentication authReq = mock(Authentication.class);
when(parent.authenticate(authReq)).thenReturn(authReq);
mgr.setParent(parent);
ProviderManager mgr = new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class)), parent);
assertSame(authReq, mgr.authenticate(authReq));
}
@Test
public void parentIsNotCalledIfAccountStatusExceptionIsThrown() throws Exception {
ProviderManager mgr = new ProviderManager();
AuthenticationProvider iThrowAccountStatusException =
createProviderWhichThrows(new AccountStatusException("", new Throwable()){});
mgr.setProviders(Arrays.asList(iThrowAccountStatusException));
AuthenticationManager parent = mock(AuthenticationManager.class);
mgr.setParent(parent);
ProviderManager mgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException), parent);
try {
mgr.authenticate(mock(Authentication.class));
fail("Expected exception");
@ -252,16 +248,15 @@ public class ProviderManagerTests {
@Test
public void authenticationExceptionFromParentOverridesPreviousOnes() throws Exception {
ProviderManager mgr = new ProviderManager();
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(
Arrays.asList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
// Set a provider that throws an exception - this is the exception we expect to be propagated
final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
mgr.setProviders(Arrays.asList(createProviderWhichThrows(new BadCredentialsException(""))));
AuthenticationManager parent = mock(AuthenticationManager.class);
when(parent.authenticate(authReq)).thenThrow(expected);
mgr.setParent(parent);
try {
mgr.authenticate(authReq);
fail("Expected exception");
@ -297,10 +292,7 @@ public class ProviderManagerTests {
List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>();
providers.add(provider1);
ProviderManager mgr = new ProviderManager();
mgr.setProviders(providers);
return mgr;
return new ProviderManager(providers);
}
//~ Inner Classes ==================================================================================================

View File

@ -79,6 +79,22 @@ 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());
}
public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint, RequestCache requestCache) {
this.authenticationEntryPoint = authenticationEntryPoint;
this.requestCache = requestCache;
}
//~ Methods ========================================================================================================
@Override
@ -173,6 +189,10 @@ public class ExceptionTranslationFilter extends GenericFilterBean {
this.accessDeniedHandler = accessDeniedHandler;
}
/**
* @deprecated Use constructor
*/
@Deprecated
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
}
@ -190,7 +210,10 @@ public class ExceptionTranslationFilter extends GenericFilterBean {
/**
* 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;

View File

@ -113,12 +113,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
protected AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private AuthenticationManager authenticationManager;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
/*
* Delay use of NullRememberMeServices until initialization so that namespace has a chance to inject
* the RememberMeServices implementation into custom implementations.
*/
private RememberMeServices rememberMeServices = null;
private RememberMeServices rememberMeServices = new NullRememberMeServices();
/**
* The URL destination that this filter intercepts and processes (usually
@ -373,6 +368,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt
}
public void setRememberMeServices(RememberMeServices rememberMeServices) {
Assert.notNull("rememberMeServices cannot be null");
this.rememberMeServices = rememberMeServices;
}

View File

@ -81,6 +81,22 @@ 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) {
this.loginFormUrl = loginFormUrl;
}
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
@ -228,7 +244,10 @@ public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoin
* 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;
}

View File

@ -59,6 +59,18 @@ public abstract class AbstractRememberMeServices implements RememberMeServices,
private Boolean useSecureCookie = null;
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
/**
* @deprecated Use cosntructor injection
*/
@Deprecated
protected AbstractRememberMeServices() {
}
protected AbstractRememberMeServices(String key, UserDetailsService userDetailsService) {
this.key = key;
this.userDetailsService = userDetailsService;
}
public void afterPropertiesSet() throws Exception {
Assert.hasLength(key);
Assert.notNull(userDetailsService, "A UserDetailsService is required");
@ -381,11 +393,21 @@ public abstract class AbstractRememberMeServices implements RememberMeServices,
return userDetailsService;
}
/**
*
* @deprecated Use constructor injection
*/
@Deprecated
public void setUserDetailsService(UserDetailsService userDetailsService) {
Assert.notNull(userDetailsService, "UserDetailsService canot be null");
this.userDetailsService = userDetailsService;
}
/**
*
* @deprecated Use constructor injection
*/
@Deprecated
public void setKey(String key) {
this.key = key;
}

View File

@ -9,6 +9,7 @@ import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.RememberMeServices;
@ -48,8 +49,19 @@ public class PersistentTokenBasedRememberMeServices extends AbstractRememberMeSe
private int seriesLength = DEFAULT_SERIES_LENGTH;
private int tokenLength = DEFAULT_TOKEN_LENGTH;
public PersistentTokenBasedRememberMeServices() throws Exception {
random = SecureRandom.getInstance("SHA1PRNG");
/**
* @deprecated Use constructor injection
*/
@Deprecated
public PersistentTokenBasedRememberMeServices() {
random = new SecureRandom();
}
public PersistentTokenBasedRememberMeServices(String key, UserDetailsService userDetailsService,
PersistentTokenRepository tokenRepository) {
super(key, userDetailsService);
random = new SecureRandom();
this.tokenRepository = tokenRepository;
}
/**
@ -132,7 +144,6 @@ public class PersistentTokenBasedRememberMeServices extends AbstractRememberMeSe
addCookie(persistentToken, request, response);
} catch (DataAccessException e) {
logger.error("Failed to save persistent token ", e);
}
}
@ -161,6 +172,10 @@ 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;
}

View File

@ -67,6 +67,19 @@ 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) {
this.authenticationManager = authenticationManager;
this.rememberMeServices = rememberMeServices;
}
//~ Methods ========================================================================================================
@Override
@ -159,10 +172,18 @@ 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;
}

View File

@ -16,6 +16,7 @@
package org.springframework.security.web.authentication.rememberme;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.codec.Utf8;
@ -81,6 +82,17 @@ 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);
}
//~ Methods ========================================================================================================
@Override

View File

@ -96,6 +96,37 @@ public class BasicAuthenticationFilter extends GenericFilterBean {
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.
*
* @param authenticationManager the bean to submit authentication requests to
*/
public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
ignoreFailure = true;
}
/**
* Creates an instance which will authenticate against the supplied {@code AuthenticationManager} and
* use the supplied {@code AuthenticationEntryPoint} to handle authentication failures.
*
* @param authenticationManager the bean to submit authentication requests to
* @param authenticationEntryPoint will be invoked when authentication fails. Typically an instance of
* {@link BasicAuthenticationEntryPoint}.
*/
public BasicAuthenticationFilter(AuthenticationManager authenticationManager,
AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationManager = authenticationManager;
this.authenticationEntryPoint = authenticationEntryPoint;
}
//~ Methods ========================================================================================================
@Override
@ -172,7 +203,7 @@ public class BasicAuthenticationFilter extends GenericFilterBean {
/**
* Decodes the header into a username and password.
* <p>
*
* @throws BadCredentialsException if the Basic header is not present or is not valid Base64
*/
private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
@ -237,6 +268,10 @@ public class BasicAuthenticationFilter extends GenericFilterBean {
return authenticationEntryPoint;
}
/**
* @deprecated Use constructor injection
*/
@Deprecated
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
}
@ -245,6 +280,10 @@ public class BasicAuthenticationFilter extends GenericFilterBean {
return authenticationManager;
}
/**
* @deprecated Use constructor injection
*/
@Deprecated
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@ -253,6 +292,11 @@ public class BasicAuthenticationFilter extends GenericFilterBean {
return ignoreFailure;
}
/**
*
* @deprecated Use the constructor which takes a single AuthenticationManager parameter
*/
@Deprecated
public void setIgnoreFailure(boolean ignoreFailure) {
this.ignoreFailure = ignoreFailure;
}

View File

@ -43,10 +43,17 @@ public class SecurityContextPersistenceFilter extends GenericFilterBean {
static final String FILTER_APPLIED = "__spring_security_scpf_applied";
private SecurityContextRepository repo = new HttpSessionSecurityContextRepository();
private SecurityContextRepository repo;
private boolean forceEagerSessionCreation = false;
public SecurityContextPersistenceFilter() {
this(new HttpSessionSecurityContextRepository());
}
public SecurityContextPersistenceFilter(SecurityContextRepository repo) {
this.repo = repo;
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
@ -92,6 +99,10 @@ 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;

View File

@ -24,7 +24,15 @@ import org.springframework.web.filter.GenericFilterBean;
*/
public class RequestCacheAwareFilter extends GenericFilterBean {
private RequestCache requestCache = new HttpSessionRequestCache();
private RequestCache requestCache;
public RequestCacheAwareFilter() {
this(new HttpSessionRequestCache());
}
public RequestCacheAwareFilter(RequestCache requestCache) {
this.requestCache = requestCache;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
@ -35,6 +43,10 @@ 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;
}

View File

@ -41,14 +41,19 @@ public class SessionManagementFilter extends GenericFilterBean {
//~ Instance fields ================================================================================================
private final SecurityContextRepository securityContextRepository;
private SessionAuthenticationStrategy sessionStrategy = new SessionFixationProtectionStrategy();
private SessionAuthenticationStrategy sessionStrategy;
private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private String invalidSessionUrl;
private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public SessionManagementFilter(SecurityContextRepository securityContextRepository) {
this(securityContextRepository, new SessionFixationProtectionStrategy());
}
public SessionManagementFilter(SecurityContextRepository securityContextRepository, SessionAuthenticationStrategy sessionStrategy) {
this.securityContextRepository = securityContextRepository;
this.sessionStrategy = sessionStrategy;
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
@ -105,7 +110,9 @@ public class SessionManagementFilter extends GenericFilterBean {
* user has been authenticated during the current request.
*
* @param sessionStrategy the strategy object. If not set, a {@link SessionFixationProtectionStrategy} is used.
* @deprecated Use constructor injection
*/
@Deprecated
public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) {
Assert.notNull(sessionStrategy, "authenticatedSessionStratedy must not be null");
this.sessionStrategy = sessionStrategy;

View File

@ -27,12 +27,13 @@ public class PersistentTokenBasedRememberMeServicesTests {
@Before
public void setUpData() throws Exception {
services = new PersistentTokenBasedRememberMeServices();
services = new PersistentTokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
new InMemoryTokenRepositoryImpl());
services.setCookieName("mycookiename");
// Default to 100 days (see SEC-1081).
services.setTokenValiditySeconds(100 * 24 * 60 * 60);
services.setUserDetailsService(
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false));
services.afterPropertiesSet();
}
@Test(expected = InvalidCookieException.class)
@ -111,7 +112,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
public void logoutClearsUsersTokenAndCookie() throws Exception {
Cookie cookie = new Cookie("mycookiename", "somevalue");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(new Cookie[] {cookie});
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
MockTokenRepository repo =
new MockTokenRepository(new PersistentRememberMeToken("joe", "series","token", new Date()));