diff --git a/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java b/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java index cb597b5ccc..b6f915c0ab 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java @@ -73,16 +73,6 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl { this.permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger); } - /** - * @deprecated Use the version which takes a {@code PermissionGrantingStrategy} argument instead. - */ - @Deprecated - public AclImpl(ObjectIdentity objectIdentity, Serializable id, AclAuthorizationStrategy aclAuthorizationStrategy, - AuditLogger auditLogger, Acl parentAcl, List loadedSids, boolean entriesInheriting, Sid owner) { - this(objectIdentity, id, aclAuthorizationStrategy, new DefaultPermissionGrantingStrategy(auditLogger), - parentAcl, loadedSids, entriesInheriting, owner); - } - /** * Full constructor, which should be used by persistence tools that do not * provide field-level access features. diff --git a/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java b/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java index d4362bdc14..64ed55f3a4 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java @@ -46,15 +46,6 @@ public class EhCacheBasedAclCache implements AclCache { //~ Constructors =================================================================================================== - /** - * @deprecated use the second constructor which injects the strategy objects. See SEC-1498. - */ - @Deprecated - public EhCacheBasedAclCache(Ehcache cache) { - Assert.notNull(cache, "Cache required"); - this.cache = cache; - } - public EhCacheBasedAclCache(Ehcache cache, PermissionGrantingStrategy permissionGrantingStrategy, AclAuthorizationStrategy aclAuthorizationStrategy) { Assert.notNull(cache, "Cache required"); diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java index b4abee260b..aaf742cb41 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java @@ -131,15 +131,20 @@ public class BasicLookupStrategy implements LookupStrategy { * @param dataSource to access the database * @param aclCache the cache where fully-loaded elements can be stored * @param aclAuthorizationStrategy authorization strategy (required) - * - * @deprecated Use the version which takes a {@code PermissionGrantingStrategy} argument instead. */ - @Deprecated public BasicLookupStrategy(DataSource dataSource, AclCache aclCache, AclAuthorizationStrategy aclAuthorizationStrategy, AuditLogger auditLogger) { this(dataSource, aclCache, aclAuthorizationStrategy, new DefaultPermissionGrantingStrategy(auditLogger)); } + /** + * Creates a new instance + * + * @param dataSource to access the database + * @param aclCache the cache where fully-loaded elements can be stored + * @param aclAuthorizationStrategy authorization strategy (required) + * @param grantingStrategy the PermissionGrantingStrategy + */ public BasicLookupStrategy(DataSource dataSource, AclCache aclCache, AclAuthorizationStrategy aclAuthorizationStrategy, PermissionGrantingStrategy grantingStrategy) { Assert.notNull(dataSource, "DataSource required"); diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java index f2f19bdbea..a3fa1f0976 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java @@ -77,7 +77,7 @@ public class AclImplTests { @Test(expected=IllegalArgumentException.class) public void constructorsRejectNullAclAuthzStrategy() throws Exception { try { - new AclImpl(objectIdentity, 1, null, mockAuditLogger, null, null, true, new PrincipalSid("joe")); + new AclImpl(objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(mockAuditLogger), null, null, true, new PrincipalSid("joe")); fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java index 4d64caebfc..4b7b540ac0 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java @@ -223,7 +223,6 @@ public class AclImplementationSecurityCheckTests { } } - @SuppressWarnings("deprecation") @Test public void testSecurityCheckPrincipalOwner() throws Exception { Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_ONE"); @@ -235,7 +234,7 @@ public class AclImplementationSecurityCheckTests { new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); - Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger(), null, null, + Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false, new PrincipalSid(auth)); try { aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL); diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java index e74ddb206c..ba7696ec43 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java @@ -84,7 +84,7 @@ public class BasicLookupStrategyTests { @Before public void initializeBeans() { - EhCacheBasedAclCache cache = new EhCacheBasedAclCache(getCache()); + EhCacheBasedAclCache cache = new EhCacheBasedAclCache(getCache(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); AclAuthorizationStrategy authorizationStrategy = new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMINISTRATOR")); strategy = new BasicLookupStrategy(dataSource, cache, authorizationStrategy, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger())); diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java index f22cff583a..4fe908b61a 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java @@ -29,16 +29,12 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.security.acls.domain.AclAuthorizationStrategy; -import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; -import org.springframework.security.acls.domain.AclImpl; -import org.springframework.security.acls.domain.ConsoleAuditLogger; -import org.springframework.security.acls.domain.EhCacheBasedAclCache; -import org.springframework.security.acls.domain.ObjectIdentityImpl; +import org.springframework.security.acls.domain.*; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.ObjectIdentity; 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.util.FieldUtils; @@ -65,7 +61,7 @@ public class EhCacheBasedAclCacheTests { @Before public void setup() { - myCache = new EhCacheBasedAclCache(cache); + myCache = new EhCacheBasedAclCache(cache, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(100)); AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( @@ -82,7 +78,7 @@ public class EhCacheBasedAclCacheTests { @Test(expected=IllegalArgumentException.class) public void constructorRejectsNullParameters() throws Exception { - new EhCacheBasedAclCache(null); + new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); } @Test diff --git a/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml b/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml index 9a79d18f8b..e8e0d8b49b 100644 --- a/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml +++ b/acl/src/test/resources/jdbcMutableAclServiceTests-context.xml @@ -22,6 +22,25 @@ + + + + + + + + + + + + + + + + + + + diff --git a/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java b/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java index bfee144194..552e1c48dc 100644 --- a/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java +++ b/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java @@ -53,10 +53,9 @@ public class AnnotationSecurityAspectTests { public final void setUp() throws Exception { MockitoAnnotations.initMocks(this); interceptor = new AspectJMethodSecurityInterceptor(); - adm = new AffirmativeBased(); AccessDecisionVoter[] voters = new AccessDecisionVoter[] {new RoleVoter(), new PreInvocationAuthorizationAdviceVoter(new ExpressionBasedPreInvocationAdvice())}; - adm.setDecisionVoters(Arrays.>asList(voters)); + adm = new AffirmativeBased(Arrays.>asList(voters)); interceptor.setAccessDecisionManager(adm); interceptor.setAuthenticationManager(authman); interceptor.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource()); diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java index b35199c582..b166fc582e 100644 --- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java +++ b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java @@ -185,15 +185,15 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia return this.authenticationUserDetailsService.loadUserDetails(token); } - @Deprecated @SuppressWarnings("unchecked") /** - * @deprecated as of 3.0. Use the {@link org.springframework.security.cas.authentication.CasAuthenticationProvider#setAuthenticationUserDetailsService(org.springframework.security.core.userdetails.AuthenticationUserDetailsService)} instead. + * Sets the UserDetailsService to use. This is a convenience method to invoke */ public void setUserDetailsService(final UserDetailsService userDetailsService) { this.authenticationUserDetailsService = new UserDetailsByNameServiceWrapper(userDetailsService); } + public void setAuthenticationUserDetailsService(final AuthenticationUserDetailsService authenticationUserDetailsService) { this.authenticationUserDetailsService = authenticationUserDetailsService; } diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java index a06b73dfad..1e56f9346d 100644 --- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java +++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java @@ -55,9 +55,7 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, In * disable the session encoding is provided for backwards compatibility. * * By default, encoding is enabled. - * @deprecated since 3.0.0 because CAS is currently on 3.3.5. */ - @Deprecated private boolean encodeServiceUrlWithSessionId = true; //~ Methods ======================================================================================================== @@ -135,9 +133,7 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, In * Sets whether to encode the service url with the session id or not. * * @param encodeServiceUrlWithSessionId whether to encode the service url with the session id or not. - * @deprecated since 3.0.0 because CAS is currently on 3.3.5. */ - @Deprecated public final void setEncodeServiceUrlWithSessionId(final boolean encodeServiceUrlWithSessionId) { this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; } @@ -146,9 +142,7 @@ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, In * Sets whether to encode the service url with the session id or not. * @return whether to encode the service url with the session id or not. * - * @deprecated since 3.0.0 because CAS is currently on 3.3.5. */ - @Deprecated protected boolean getEncodeServiceUrlWithSessionId() { return this.encodeServiceUrlWithSessionId; } diff --git a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java index ed2e53126d..a954e8f252 100644 --- a/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java +++ b/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java @@ -38,6 +38,8 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** @@ -170,7 +172,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil /** * The last portion of the receptor url, i.e. /proxy/receptor */ - private String proxyReceptorUrl; + private RequestMatcher proxyReceptorMatcher; /** * The backing storage to store ProxyGrantingTicket requests. @@ -254,7 +256,6 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil /** * Overridden to provide proxying capabilities. */ - @Override protected boolean requiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) { final boolean serviceTicketRequest = serviceTicketRequest(request, response); final boolean result = serviceTicketRequest || proxyReceptorRequest(request) || (proxyTicketRequest(serviceTicketRequest, request)); @@ -286,7 +287,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil } public final void setProxyReceptorUrl(final String proxyReceptorUrl) { - this.proxyReceptorUrl = proxyReceptorUrl; + this.proxyReceptorMatcher = new AntPathRequestMatcher("/**" + proxyReceptorUrl); } public final void setProxyGrantingTicketStorage( @@ -343,8 +344,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil * @return */ private boolean proxyReceptorRequest(final HttpServletRequest request) { - final String requestUri = request.getRequestURI(); - final boolean result = proxyReceptorConfigured() && requestUri.endsWith(this.proxyReceptorUrl); + final boolean result = proxyReceptorConfigured() && proxyReceptorMatcher.matches(request); if(logger.isDebugEnabled()) { logger.debug("proxyReceptorRequest = "+result); } @@ -357,7 +357,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil * @return */ private boolean proxyReceptorConfigured() { - final boolean result = this.proxyGrantingTicketStorage != null && !CommonUtils.isEmpty(this.proxyReceptorUrl); + final boolean result = this.proxyGrantingTicketStorage != null && proxyReceptorMatcher != null; if(logger.isDebugEnabled()) { logger.debug("proxyReceptorConfigured = "+result); } diff --git a/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java b/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java index d144a34b49..813dab91fb 100644 --- a/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java +++ b/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java @@ -20,10 +20,6 @@ import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.cas.ServiceProperties; import org.springframework.util.Assert; @@ -39,7 +35,7 @@ import org.springframework.util.Assert; * @author Rob Winch */ public class ServiceAuthenticationDetailsSource implements AuthenticationDetailsSource, ApplicationContextAware { + ServiceAuthenticationDetails> { //~ Instance fields ================================================================================================ private final Pattern artifactPattern; @@ -48,15 +44,6 @@ public class ServiceAuthenticationDetailsSource implements AuthenticationDetails //~ Constructors =================================================================================================== - /** - * Creates an implementation that uses the default CAS artifactParameterName. - * @deprecated Use ServiceAuthenticationDetailsSource(ServiceProperties) - */ - @Deprecated - public ServiceAuthenticationDetailsSource() { - this(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); - } - /** * Creates an implementation that uses the specified ServiceProperites and the default CAS artifactParameterName. * @@ -66,19 +53,6 @@ public class ServiceAuthenticationDetailsSource implements AuthenticationDetails this(serviceProperties,ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); } - /** - * Creates an implementation that uses the specified artifactParameterName - * - * @param artifactParameterName - * the artifactParameterName that is removed from the current - * URL. The result becomes the service url. Cannot be null and - * cannot be an empty String. - * @deprecated Use ServiceAuthenticationDetailsSource(ServiceProperties,String) - */ - public ServiceAuthenticationDetailsSource(final String artifactParameterName) { - this.artifactPattern = DefaultServiceAuthenticationDetails.createArtifactPattern(artifactParameterName); - } - /** * Creates an implementation that uses the specified artifactParameterName * @@ -107,10 +81,4 @@ public class ServiceAuthenticationDetailsSource implements AuthenticationDetails throw new RuntimeException(e); } } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - if(serviceProperties == null) { - serviceProperties = applicationContext.getBean(ServiceProperties.class); - } - } } \ No newline at end of file diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java index f5967b33c9..60c29e9827 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java @@ -63,7 +63,6 @@ public class CasAuthenticationFilterTests { @Test public void testGettersSetters() { CasAuthenticationFilter filter = new CasAuthenticationFilter(); - assertEquals("/j_spring_cas_security_check", filter.getFilterProcessesUrl()); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); filter.setProxyReceptorUrl("/someurl"); filter.setServiceProperties(new ServiceProperties()); @@ -71,7 +70,8 @@ public class CasAuthenticationFilterTests { @Test public void testNormalOperation() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/j_spring_cas_security_check"); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("/j_spring_cas_security_check"); request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ"); CasAuthenticationFilter filter = new CasAuthenticationFilter(); @@ -101,11 +101,13 @@ public class CasAuthenticationFilterTests { @Test public void testRequiresAuthenticationFilterProcessUrl() { + String url = "/login/cas"; CasAuthenticationFilter filter = new CasAuthenticationFilter(); + filter.setFilterProcessesUrl(url); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - request.setRequestURI(filter.getFilterProcessesUrl()); + request.setServletPath(url); assertTrue(filter.requiresAuthentication(request, response)); } @@ -115,13 +117,13 @@ public class CasAuthenticationFilterTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - request.setRequestURI("/pgtCallback"); + request.setServletPath("/pgtCallback"); assertFalse(filter.requiresAuthentication(request, response)); - filter.setProxyReceptorUrl(request.getRequestURI()); + filter.setProxyReceptorUrl(request.getServletPath()); assertFalse(filter.requiresAuthentication(request, response)); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); assertTrue(filter.requiresAuthentication(request, response)); - request.setRequestURI("/other"); + request.setServletPath("/other"); assertFalse(filter.requiresAuthentication(request, response)); } @@ -130,15 +132,17 @@ public class CasAuthenticationFilterTests { ServiceProperties properties = new ServiceProperties(); properties.setAuthenticateAllArtifacts(true); + String url = "/login/cas"; CasAuthenticationFilter filter = new CasAuthenticationFilter(); + filter.setFilterProcessesUrl(url); filter.setServiceProperties(properties); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - request.setRequestURI(filter.getFilterProcessesUrl()); + request.setServletPath(url); assertTrue(filter.requiresAuthentication(request, response)); - request.setRequestURI("/other"); + request.setServletPath("/other"); assertFalse(filter.requiresAuthentication(request, response)); request.setParameter(properties.getArtifactParameter(), "value"); assertTrue(filter.requiresAuthentication(request, response)); @@ -156,9 +160,9 @@ public class CasAuthenticationFilterTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - request.setRequestURI("/pgtCallback"); + request.setServletPath("/pgtCallback"); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - filter.setProxyReceptorUrl(request.getRequestURI()); + filter.setProxyReceptorUrl(request.getServletPath()); assertNull(filter.attemptAuthentication(request, response)); } @@ -172,7 +176,7 @@ public class CasAuthenticationFilterTests { serviceProperties.setAuthenticateAllArtifacts(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("ticket", "ST-1-123"); - request.setRequestURI("/authenticate"); + request.setServletPath("/authenticate"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); @@ -189,7 +193,7 @@ public class CasAuthenticationFilterTests { verifyZeroInteractions(successHandler); // validate for when the filterProcessUrl matches - filter.setFilterProcessesUrl(request.getRequestURI()); + filter.setFilterProcessesUrl(request.getServletPath()); SecurityContextHolder.clearContext(); filter.doFilter(request,response,chain); verifyNoMoreInteractions(chain); @@ -204,9 +208,9 @@ public class CasAuthenticationFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); - request.setRequestURI("/pgtCallback"); + request.setServletPath("/pgtCallback"); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); - filter.setProxyReceptorUrl(request.getRequestURI()); + filter.setProxyReceptorUrl(request.getServletPath()); filter.doFilter(request,response,chain); verifyZeroInteractions(chain); diff --git a/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java b/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java index f8d5d648e3..2243c50956 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java @@ -115,14 +115,6 @@ public class DefaultServiceAuthenticationDetailsTests { assertEquals("https://example.com/cas-sample/secure/",details.getServiceUrl()); } - @Test - public void getServiceUrlDoesNotUseHostHeaderPassivity() { - casServiceUrl = "https://example.com/j_spring_security_cas"; - request.setServerName("evil.com"); - ServiceAuthenticationDetails details = loadServiceAuthenticationDetails("defaultserviceauthenticationdetails-passivity.xml"); - assertEquals("https://example.com/cas-sample/secure/", details.getServiceUrl()); - } - @Test public void getServiceUrlDoesNotUseHostHeaderExplicit() { casServiceUrl = "https://example.com/j_spring_security_cas"; diff --git a/config/src/main/java/org/springframework/security/config/Elements.java b/config/src/main/java/org/springframework/security/config/Elements.java index 7cd1216c16..99ee4fd199 100644 --- a/config/src/main/java/org/springframework/security/config/Elements.java +++ b/config/src/main/java/org/springframework/security/config/Elements.java @@ -49,8 +49,6 @@ public abstract class Elements { public static final String JEE = "jee"; public static final String FILTER_SECURITY_METADATA_SOURCE = "filter-security-metadata-source"; public static final String METHOD_SECURITY_METADATA_SOURCE = "method-security-metadata-source"; - @Deprecated - public static final String FILTER_INVOCATION_DEFINITION_SOURCE = "filter-invocation-definition-source"; public static final String LDAP_PASSWORD_COMPARE = "password-compare"; public static final String DEBUG = "debug"; public static final String HTTP_FIREWALL = "http-firewall"; diff --git a/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java b/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java index e3e24ceecf..a409339c79 100644 --- a/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java +++ b/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java @@ -173,7 +173,6 @@ public final class SecurityNamespaceHandler implements NamespaceHandler { parsers.put(Elements.DEBUG, new DebugBeanDefinitionParser()); parsers.put(Elements.HTTP, new HttpSecurityBeanDefinitionParser()); parsers.put(Elements.HTTP_FIREWALL, new HttpFirewallBeanDefinitionParser()); - parsers.put(Elements.FILTER_INVOCATION_DEFINITION_SOURCE, new FilterInvocationSecurityMetadataSourceParser()); parsers.put(Elements.FILTER_SECURITY_METADATA_SOURCE, new FilterInvocationSecurityMetadataSourceParser()); parsers.put(Elements.FILTER_CHAIN, new FilterChainBeanDefinitionParser()); filterChainMapBDD = new FilterChainMapBeanDefinitionDecorator(); diff --git a/config/src/main/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParser.java index e576cf4c27..2ed8017cc0 100644 --- a/config/src/main/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/authentication/AuthenticationManagerBeanDefinitionParser.java @@ -52,7 +52,6 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition String alias = element.getAttribute(ATT_ALIAS); - checkForDeprecatedSessionControllerRef(element, pc); List providers = new ManagedList(); NamespaceHandlerResolver resolver = pc.getReaderContext().getNamespaceHandlerResolver(); @@ -113,16 +112,6 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition return null; } - private void checkForDeprecatedSessionControllerRef(Element element, ParserContext pc) { - final String ATT_SESSION_CONTROLLER_REF = "session-controller-ref"; - - if (StringUtils.hasText(element.getAttribute(ATT_SESSION_CONTROLLER_REF))) { - pc.getReaderContext().warning(ATT_SESSION_CONTROLLER_REF + " is not supported in Spring Security " + - " 3.0 and will be ignored. Use the attribute on the element instead.", - pc.extractSource(element)); - } - } - /** * Provider which doesn't provide any service. Only used to prevent a configuration exception if the provider list * is empty (usually because a child ProviderManager from the <http> namespace, such as OpenID, is expected diff --git a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java index bbd74b6669..ff1d665836 100644 --- a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java +++ b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java @@ -84,7 +84,6 @@ final class AuthenticationConfigBuilder { private static final String ATT_AUTO_CONFIG = "auto-config"; - private static final String ATT_ACCESS_DENIED_PAGE = "access-denied-page"; private static final String ATT_ACCESS_DENIED_ERROR_PAGE = "error-page"; private static final String ATT_ENTRY_POINT_REF = "entry-point-ref"; @@ -587,20 +586,9 @@ final class AuthenticationConfigBuilder { } private BeanMetadataElement createAccessDeniedHandler(Element element, ParserContext pc) { - String accessDeniedPage = element.getAttribute(ATT_ACCESS_DENIED_PAGE); - WebConfigUtils.validateHttpRedirect(accessDeniedPage, pc, pc.extractSource(element)); Element accessDeniedElt = DomUtils.getChildElementByTagName(element, Elements.ACCESS_DENIED_HANDLER); BeanDefinitionBuilder accessDeniedHandler = BeanDefinitionBuilder.rootBeanDefinition(AccessDeniedHandlerImpl.class); - if (StringUtils.hasText(accessDeniedPage)) { - if (accessDeniedElt != null) { - pc.getReaderContext().error("The attribute " + ATT_ACCESS_DENIED_PAGE + - " cannot be used with <" + Elements.ACCESS_DENIED_HANDLER + ">", pc.extractSource(accessDeniedElt)); - } - - accessDeniedHandler.addPropertyValue("errorPage", accessDeniedPage); - } - if (accessDeniedElt != null) { String errorPage = accessDeniedElt.getAttribute("error-page"); String ref = accessDeniedElt.getAttribute("ref"); diff --git a/config/src/main/java/org/springframework/security/config/http/FilterChainMapBeanDefinitionDecorator.java b/config/src/main/java/org/springframework/security/config/http/FilterChainMapBeanDefinitionDecorator.java index 7d8696509f..e186660285 100644 --- a/config/src/main/java/org/springframework/security/config/http/FilterChainMapBeanDefinitionDecorator.java +++ b/config/src/main/java/org/springframework/security/config/http/FilterChainMapBeanDefinitionDecorator.java @@ -5,14 +5,17 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.springframework.beans.BeanMetadataElement; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.xml.BeanDefinitionDecorator; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.security.config.Elements; +import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; @@ -29,7 +32,7 @@ public class FilterChainMapBeanDefinitionDecorator implements BeanDefinitionDeco public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder holder, ParserContext parserContext) { BeanDefinition filterChainProxy = holder.getBeanDefinition(); - Map filterChainMap = new LinkedHashMap(); + ManagedList securityFilterChains = new ManagedList(); Element elt = (Element)node; MatcherType matcherType = MatcherType.fromElement(elt); @@ -53,7 +56,7 @@ public class FilterChainMapBeanDefinitionDecorator implements BeanDefinitionDeco BeanDefinition matcher = matcherType.createMatcher(path, null); if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { - filterChainMap.put(matcher, Collections.EMPTY_LIST); + securityFilterChains.add(createSecurityFilterChain(matcher, new ManagedList(0))); } else { String[] filterBeanNames = StringUtils.tokenizeToStringArray(filters, ","); ManagedList filterChain = new ManagedList(filterBeanNames.length); @@ -62,15 +65,19 @@ public class FilterChainMapBeanDefinitionDecorator implements BeanDefinitionDeco filterChain.add(new RuntimeBeanReference(name)); } - filterChainMap.put(matcher, filterChain); + securityFilterChains.add(createSecurityFilterChain(matcher, filterChain)); } } - ManagedMap map = new ManagedMap(filterChainMap.size()); - map.putAll(filterChainMap); - - filterChainProxy.getPropertyValues().addPropertyValue("filterChainMap", map); + filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue(securityFilterChains); return holder; } + + private BeanDefinition createSecurityFilterChain(BeanDefinition matcher, ManagedList filters) { + BeanDefinitionBuilder sfc = BeanDefinitionBuilder.rootBeanDefinition(DefaultSecurityFilterChain.class); + sfc.addConstructorArgValue(matcher); + sfc.addConstructorArgValue(filters); + return sfc.getBeanDefinition(); + } } diff --git a/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java b/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java index 3dc5c27f3d..d81ab4a41b 100644 --- a/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java +++ b/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java @@ -128,14 +128,15 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit BeanDefinition matcher = matcherType.createMatcher(path, method); BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class); - attributeBuilder.addConstructorArgValue(access); if (useExpressions) { logger.info("Creating access control expression attribute '" + access + "' for " + path); // The single expression will be parsed later by the ExpressionFilterInvocationSecurityMetadataSource - attributeBuilder.setFactoryMethod("createSingleAttributeList"); + attributeBuilder.addConstructorArgValue(new String[] { access }); + attributeBuilder.setFactoryMethod("createList"); } else { + attributeBuilder.addConstructorArgValue(access); attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString"); } diff --git a/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java index 216f79a207..42f9e3e9a4 100644 --- a/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java @@ -151,7 +151,7 @@ public class FormLoginBeanDefinitionParser { this.loginProcessingUrl = loginUrl; - BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.authentication.logout.LogoutFilter$FilterProcessUrlRequestMatcher"); + BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.util.matcher.AntPathRequestMatcher"); matcherBuilder.addConstructorArgValue(loginUrl); filterBuilder.addPropertyValue("requiresAuthenticationRequestMatcher", matcherBuilder.getBeanDefinition()); diff --git a/config/src/main/java/org/springframework/security/config/http/LogoutBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/LogoutBeanDefinitionParser.java index eb11751686..aa1c8c1a66 100644 --- a/config/src/main/java/org/springframework/security/config/http/LogoutBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/LogoutBeanDefinitionParser.java @@ -119,16 +119,13 @@ class LogoutBeanDefinitionParser implements BeanDefinitionParser { } private BeanDefinition getLogoutRequestMatcher(String logoutUrl) { + BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.util.matcher.AntPathRequestMatcher"); + matcherBuilder.addConstructorArgValue(logoutUrl); if(this.csrfEnabled) { - BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.util.matcher.AntPathRequestMatcher"); - matcherBuilder.addConstructorArgValue(logoutUrl); matcherBuilder.addConstructorArgValue("POST"); - return matcherBuilder.getBeanDefinition(); - } else { - BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter$FilterProcessUrlRequestMatcher"); - matcherBuilder.addConstructorArgValue(logoutUrl); - return matcherBuilder.getBeanDefinition(); } + + return matcherBuilder.getBeanDefinition(); } ManagedList getLogoutHandlers() { diff --git a/config/src/main/java/org/springframework/security/config/http/MatcherType.java b/config/src/main/java/org/springframework/security/config/http/MatcherType.java index a115dc602a..e20162bf69 100644 --- a/config/src/main/java/org/springframework/security/config/http/MatcherType.java +++ b/config/src/main/java/org/springframework/security/config/http/MatcherType.java @@ -1,7 +1,5 @@ package org.springframework.security.config.http; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.RootBeanDefinition; @@ -23,10 +21,7 @@ public enum MatcherType { regex (RegexRequestMatcher.class), ciRegex (RegexRequestMatcher.class); - private static final Log logger = LogFactory.getLog(MatcherType.class); - private static final String ATT_MATCHER_TYPE = "request-matcher"; - private static final String ATT_PATH_TYPE = "path-type"; private final Class type; @@ -56,11 +51,6 @@ public enum MatcherType { return valueOf(elt.getAttribute(ATT_MATCHER_TYPE)); } - if (StringUtils.hasText(elt.getAttribute(ATT_PATH_TYPE))) { - logger.warn("'" + ATT_PATH_TYPE + "' is deprecated. Please use '" + ATT_MATCHER_TYPE +"' instead."); - return valueOf(elt.getAttribute(ATT_PATH_TYPE)); - } - return ant; } } diff --git a/config/src/main/java/org/springframework/security/config/message/MessageSecurityBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/message/MessageSecurityBeanDefinitionParser.java index 6ab0a2c23a..cd946b815b 100644 --- a/config/src/main/java/org/springframework/security/config/message/MessageSecurityBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/message/MessageSecurityBeanDefinitionParser.java @@ -137,7 +137,7 @@ public final class MessageSecurityBeanDefinitionParser implements BeanDefinition static class MessageSecurityPostProcessor implements BeanDefinitionRegistryPostProcessor { private static final String CLIENT_INBOUND_CHANNEL_BEAN_ID = "clientInboundChannel"; - + private static final String INTERCEPTORS_PROP = "interceptors"; private static final String CUSTOM_ARG_RESOLVERS_PROP = "customArgumentResolvers"; @@ -148,7 +148,6 @@ public final class MessageSecurityBeanDefinitionParser implements BeanDefinition this.inboundSecurityInterceptorId = inboundSecurityInterceptorId; } - @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { String[] beanNames = registry.getBeanDefinitionNames(); for(String beanName : beanNames) { @@ -181,7 +180,6 @@ public final class MessageSecurityBeanDefinitionParser implements BeanDefinition inboundChannel.getPropertyValues().add(INTERCEPTORS_PROP, interceptors); } - @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } diff --git a/config/src/main/resources/org/springframework/security/config/spring-security-4.0.rnc b/config/src/main/resources/org/springframework/security/config/spring-security-4.0.rnc index 22a3ccb25e..572d8e8266 100644 --- a/config/src/main/resources/org/springframework/security/config/spring-security-4.0.rnc +++ b/config/src/main/resources/org/springframework/security/config/spring-security-4.0.rnc @@ -12,11 +12,8 @@ base64 = ## Whether a string should be base64 encoded attribute base64 {xsd:boolean} request-matcher = - ## Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. + ## Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. attribute request-matcher {"ant" | "regex" | "ciRegex"} -path-type = - ## Deprecated. Use request-matcher instead. - attribute path-type {"ant" | "regex"} port = ## Specifies an IP port number. Used to configure an embedded LDAP server, for example. attribute port { xsd:positiveInteger } @@ -323,9 +320,6 @@ http.attlist &= attribute security-context-repository-ref {xsd:token}? http.attlist &= request-matcher? -http.attlist &= - ## Deprecated. Use request-matcher instead. - path-type? http.attlist &= ## Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by accessing the Spring SecurityContext. Defaults to "true". attribute servlet-api-provision {xsd:boolean}? @@ -344,9 +338,6 @@ http.attlist &= http.attlist &= ## Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults to "true" attribute once-per-request {xsd:boolean}? -http.attlist &= - ## Deprecated in favour of the access-denied-handler element. - attribute access-denied-page {xsd:token}? http.attlist &= ## Prevents the jsessionid parameter from being added to rendered URLs. attribute disable-url-rewriting {xsd:boolean}? @@ -476,9 +467,6 @@ openid-attribute.attlist &= filter-chain-map = ## Used to explicitly configure a FilterChainProxy instance with a FilterChainMap element filter-chain-map {filter-chain-map.attlist, filter-chain+} -filter-chain-map.attlist &= - ## Deprecated. Use request-matcher instead. - path-type? filter-chain-map.attlist &= request-matcher? @@ -508,16 +496,9 @@ fsmds.attlist &= fsmds.attlist &= ## Compare after forcing to lowercase attribute lowercase-comparisons {xsd:boolean}? -fsmds.attlist &= - ## Deprecate. Use request-matcher instead. - path-type? fsmds.attlist &= request-matcher? -filter-invocation-definition-source = - ## Deprecated synonym for filter-security-metadata-source - element filter-invocation-definition-source {fsmds.attlist, intercept-url+} - http-basic = ## Adds support for basic authentication element http-basic {http-basic.attlist, empty} diff --git a/config/src/main/resources/org/springframework/security/config/spring-security-4.0.xsd b/config/src/main/resources/org/springframework/security/config/spring-security-4.0.xsd index 1e7b23d94a..1c9fd007f5 100644 --- a/config/src/main/resources/org/springframework/security/config/spring-security-4.0.xsd +++ b/config/src/main/resources/org/springframework/security/config/spring-security-4.0.xsd @@ -34,9 +34,9 @@ - Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming - requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular - expressions and 'ciRegex' for case-insensitive regular expressions. + Defines the strategy use for matching incoming requests. Currently the options are 'ant' + (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for + case-insensitive regular expressions. @@ -48,20 +48,6 @@ - - - - Deprecated. Use request-matcher instead. - - - - - - - - - - @@ -1160,9 +1146,9 @@ - Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming - requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular - expressions and 'ciRegex' for case-insensitive regular expressions. + Defines the strategy use for matching incoming requests. Currently the options are 'ant' + (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for + case-insensitive regular expressions. @@ -1173,18 +1159,6 @@ - - - Deprecated. Use request-matcher instead. - - - - - - - - - Provides versions of HttpServletRequest security methods such as isUserInRole() and @@ -1228,12 +1202,6 @@ - - - Deprecated in favour of the access-denied-handler element. - - - Prevents the jsessionid parameter from being added to rendered URLs. @@ -1534,23 +1502,11 @@ - - - Deprecated. Use request-matcher instead. - - - - - - - - - - Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming - requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular - expressions and 'ciRegex' for case-insensitive regular expressions. + Defines the strategy use for matching incoming requests. Currently the options are 'ant' + (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for + case-insensitive regular expressions. @@ -1657,23 +1613,11 @@ - - - Deprecated. Use request-matcher instead. - - - - - - - - - - Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming - requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular - expressions and 'ciRegex' for case-insensitive regular expressions. + Defines the strategy use for matching incoming requests. Currently the options are 'ant' + (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for + case-insensitive regular expressions. @@ -1685,26 +1629,6 @@ - - - Deprecated synonym for filter-security-metadata-source - - - - - - - Specifies the access attributes and/or filter list for a particular set of URLs. - - - - - - - - - - diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.groovy index a20ad1a92c..1cd0c9a58c 100644 --- a/config/src/test/groovy/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.groovy @@ -326,10 +326,6 @@ public class NamespaceHttpTests extends BaseSpringSpec { } } - // http@path-type is not available (instead request matcher instances are used) - - // http@pattern is not available (instead see the tests http@request-matcher-ref ant or http@request-matcher-ref regex) - def "http@realm"() { setup: loadConfig(RealmConfig) diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.groovy index cb38183da9..dbf34ff547 100644 --- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.groovy @@ -38,7 +38,6 @@ import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler -import org.springframework.security.web.access.expression.WebSecurityExpressionHandler import org.springframework.security.web.util.matcher.AnyRequestMatcher import org.springframework.test.util.ReflectionTestUtils @@ -200,21 +199,20 @@ class WebSecurityConfigurationTests extends BaseSpringSpec { def "Override webSecurityExpressionHandler"() { setup: - WebSecurityExpressionHandler expressionHandler = Mock() + SecurityExpressionHandler expressionHandler = Mock() ExpressionParser parser = Mock() WebSecurityExpressionHandlerConfig.EH = expressionHandler when: loadConfig(WebSecurityExpressionHandlerConfig) then: - context.getBean(WebSecurityExpressionHandler) == expressionHandler + context.getBean(SecurityExpressionHandler) == expressionHandler 1 * expressionHandler.getExpressionParser() >> parser } @EnableWebSecurity @Configuration static class WebSecurityExpressionHandlerConfig extends WebSecurityConfigurerAdapter { - @SuppressWarnings("deprecation") - static WebSecurityExpressionHandler EH + static SecurityExpressionHandler EH @Override public void configure(WebSecurity web) throws Exception { @@ -234,7 +232,7 @@ class WebSecurityConfigurationTests extends BaseSpringSpec { when: loadConfig(WebSecurityExpressionHandlerDefaultsConfig) then: - WebSecurityExpressionHandler wseh = context.getBean(WebSecurityExpressionHandler) + SecurityExpressionHandler wseh = context.getBean(SecurityExpressionHandler) wseh instanceof DefaultWebSecurityExpressionHandler } diff --git a/config/src/test/groovy/org/springframework/security/config/http/AccessDeniedConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/AccessDeniedConfigTests.groovy index 7ad7beeef9..33d0e5b27b 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/AccessDeniedConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/AccessDeniedConfigTests.groovy @@ -10,20 +10,11 @@ import org.springframework.security.web.access.ExceptionTranslationFilter * @author Luke Taylor */ class AccessDeniedConfigTests extends AbstractHttpConfigTests { - private static final String ACCESS_DENIED_PAGE = 'access-denied-page'; - - def accessDeniedPageAttributeIsSupported() { - httpAccessDeniedPage ('/accessDenied') { } - createAppContext(); - - expect: - getFilter(ExceptionTranslationFilter.class).accessDeniedHandler.errorPage == '/accessDenied' - - } - def invalidAccessDeniedUrlIsDetected() { when: - httpAccessDeniedPage ('noLeadingSlash') { } + httpAutoConfig() { + 'access-denied-handler'('error-page':'noLeadingSlash') + } createAppContext(); then: thrown(BeanCreationException) @@ -43,16 +34,6 @@ class AccessDeniedConfigTests extends AbstractHttpConfigTests { filter.accessDeniedHandler == adh } - def void accessDeniedPageAndAccessDeniedHandlerAreMutuallyExclusive() { - when: - httpAccessDeniedPage ('/accessDenied') { - 'access-denied-handler'('error-page': '/go-away') - } - createAppContext(); - then: - thrown(BeanDefinitionParsingException) - } - def void accessDeniedHandlerPageAndRefAreMutuallyExclusive() { when: httpAutoConfig { @@ -63,8 +44,4 @@ class AccessDeniedConfigTests extends AbstractHttpConfigTests { then: thrown(BeanDefinitionParsingException) } - - def httpAccessDeniedPage(String page, Closure c) { - xml.http(['auto-config': 'true', 'access-denied-page': page], c) - } } diff --git a/config/src/test/groovy/org/springframework/security/config/http/CsrfConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/CsrfConfigTests.groovy index d2081733ea..2d03eb42cc 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/CsrfConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/CsrfConfigTests.groovy @@ -156,7 +156,7 @@ class CsrfConfigTests extends AbstractHttpConfigTests { when: "authenticate successfully" response = new MockHttpServletResponse() request = new MockHttpServletRequest(session: request.session) - request.requestURI = "/j_spring_security_check" + request.servletPath = "/j_spring_security_check" request.setParameter(token.parameterName,token.token) request.setParameter("j_username","user") request.setParameter("j_password","password") @@ -190,7 +190,7 @@ class CsrfConfigTests extends AbstractHttpConfigTests { when: "authenticate successfully" response = new MockHttpServletResponse() request = new MockHttpServletRequest(session: request.session) - request.requestURI = "/j_spring_security_check" + request.servletPath = "/j_spring_security_check" request.setParameter(token.parameterName,token.token) request.setParameter("j_username","user") request.setParameter("j_password","password") @@ -281,7 +281,7 @@ class CsrfConfigTests extends AbstractHttpConfigTests { request.method = "POST" request.setParameter("j_username","user") request.setParameter("j_password","password") - request.requestURI = "/j_spring_security_check" + request.servletPath = "/j_spring_security_check" when: springSecurityFilterChain.doFilter(request,response,chain) then: diff --git a/config/src/test/groovy/org/springframework/security/config/http/FormLoginConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/FormLoginConfigTests.groovy index 95523f9624..75dbb95fbf 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/FormLoginConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/FormLoginConfigTests.groovy @@ -104,18 +104,4 @@ class FormLoginConfigTests extends AbstractHttpConfigTests { apf.usernameParameter == 'xname'; apf.passwordParameter == 'xpass' } - - def 'SEC-2455: http@login-processing-url'() { - when: - xml.http { - 'form-login'('login-processing-url':'/authenticate') - } - createAppContext() - - def apf = getFilter(UsernamePasswordAuthenticationFilter); - - then: - apf.filterProcessesUrl == null // SEC-2455 setFilterProcessesUrl was not invoked - FieldUtils.getFieldValue(apf,'requiresAuthenticationRequestMatcher.filterProcessesUrl') == '/authenticate' - } } diff --git a/config/src/test/groovy/org/springframework/security/config/http/HttpOpenIDConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/HttpOpenIDConfigTests.groovy index f2403092c6..b7784fa1e5 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/HttpOpenIDConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/HttpOpenIDConfigTests.groovy @@ -116,7 +116,7 @@ class OpenIDConfigTests extends AbstractHttpConfigTests { then: "Remember-me choice is added to page" response.getContentAsString().contains(AbstractRememberMeServices.DEFAULT_PARAMETER) when: "Login is submitted with remember-me selected" - request.setRequestURI("/j_spring_openid_security_check") + request.servletPath = "/j_spring_openid_security_check" request.setParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "http://hey.openid.com/") request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "on") response = new MockHttpServletResponse(); diff --git a/config/src/test/groovy/org/springframework/security/config/http/InterceptUrlConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/InterceptUrlConfigTests.groovy index 18df329acb..d0af38accf 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/InterceptUrlConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/InterceptUrlConfigTests.groovy @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.security.config.http; +package org.springframework.security.config.http +import org.springframework.security.crypto.codec.Base64; import java.security.Principal @@ -125,4 +126,39 @@ class InterceptUrlConfigTests extends AbstractHttpConfigTests { then: 'The response is unauthorized' response.status == HttpServletResponse.SC_UNAUTHORIZED } + + def "intercept-url supports hasAnyRoles"() { + setup: + MockHttpServletRequest request = new MockHttpServletRequest(method:'GET') + MockHttpServletResponse response = new MockHttpServletResponse() + MockFilterChain chain = new MockFilterChain() + xml.http('use-expressions':true) { + 'http-basic'() + 'intercept-url'(pattern: '/**', access: "hasAnyRole('ROLE_DEVELOPER','ROLE_USER')") + csrf(disabled:true) + } + when: + createAppContext() + then: 'no error' + noExceptionThrown() + when: 'ROLE_USER can access' + login(request, 'user', 'password') + springSecurityFilterChain.doFilter(request,response,chain) + then: 'The response is OK' + response.status == HttpServletResponse.SC_OK + when: 'ROLE_A cannot access' + request = new MockHttpServletRequest(method:'GET') + response = new MockHttpServletResponse() + chain = new MockFilterChain() + login(request, 'bob', 'bobspassword') + springSecurityFilterChain.doFilter(request,response,chain) + then: 'The response is Forbidden' + response.status == HttpServletResponse.SC_FORBIDDEN + + } + + def login(MockHttpServletRequest request, String username, String password) { + String toEncode = username + ':' + password + request.addHeader('Authorization','Basic ' + new String(Base64.encode(toEncode.getBytes('UTF-8')))) + } } \ No newline at end of file diff --git a/config/src/test/groovy/org/springframework/security/config/http/LogoutConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/LogoutConfigTests.groovy deleted file mode 100644 index 7820d171a3..0000000000 --- a/config/src/test/groovy/org/springframework/security/config/http/LogoutConfigTests.groovy +++ /dev/null @@ -1,26 +0,0 @@ -package org.springframework.security.config.http - -import org.springframework.security.util.FieldUtils -import org.springframework.security.web.authentication.logout.LogoutFilter - -/** - * - * @author Rob Winch - */ -class LogoutConfigTests extends AbstractHttpConfigTests { - - def 'SEC-2455: logout@logout-url'() { - when: - httpAutoConfig { - 'logout'('logout-url':'/logout') - csrf(disabled:true) - } - createAppContext() - - def lf = getFilter(LogoutFilter); - - then: - lf.filterProcessesUrl == null // SEC-2455 setFilterProcessesUrl was not invoked - FieldUtils.getFieldValue(lf,'logoutRequestMatcher.filterProcessesUrl') == '/logout' - } -} \ No newline at end of file diff --git a/config/src/test/groovy/org/springframework/security/config/http/PlaceHolderAndELConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/PlaceHolderAndELConfigTests.groovy index 7e57d9750d..658548aaba 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/PlaceHolderAndELConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/PlaceHolderAndELConfigTests.groovy @@ -135,7 +135,9 @@ class PlaceHolderAndELConfigTests extends AbstractHttpConfigTests { def accessDeniedPageWorksWithPlaceholders() { System.setProperty("accessDenied", "/go-away"); - xml.http('auto-config': 'true', 'access-denied-page': '${accessDenied}') + xml.http('auto-config': 'true') { + 'access-denied-handler'('error-page' : '${accessDenied}') {} + } createAppContext(); expect: diff --git a/config/src/test/groovy/org/springframework/security/config/http/SessionManagementConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/SessionManagementConfigTests.groovy index 61b0d99b05..e7e60408be 100644 --- a/config/src/test/groovy/org/springframework/security/config/http/SessionManagementConfigTests.groovy +++ b/config/src/test/groovy/org/springframework/security/config/http/SessionManagementConfigTests.groovy @@ -285,7 +285,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession(); - request.setRequestURI("/j_spring_security_check"); + request.servletPath = "/j_spring_security_check" request.setMethod("POST"); request.setParameter("j_username", "user"); request.setParameter("j_password", "password"); diff --git a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java index ea6496ed89..d88dde9e13 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationProviderBeanDefinitionParserTests.java @@ -8,7 +8,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio import org.springframework.security.authentication.dao.ReflectionSaltSource; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.BeanIds; -import org.springframework.security.config.authentication.AuthenticationProviderBeanDefinitionParser; import org.springframework.security.config.util.InMemoryXmlApplicationContext; import org.springframework.security.util.FieldUtils; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; @@ -153,8 +152,12 @@ public class AuthenticationProviderBeanDefinitionParserTests { " " + " " + " " + - " " + + " class='org.springframework.security.provisioning.InMemoryUserDetailsManager'>" + + " " + + " " + + " f117f0862384e9497ff4f470e3522606,ROLE_A" + + " " + + " " + " "); getProvider().authenticate(bob); } diff --git a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java index d5561b9d7f..bf5d1ad082 100644 --- a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java +++ b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java @@ -98,7 +98,7 @@ public class SessionManagementConfigServlet31Tests { Method method = mock(Method.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession(); - request.setRequestURI("/j_spring_security_check"); + request.setServletPath("/j_spring_security_check"); request.setMethod("POST"); request.setParameter("j_username", "user"); request.setParameter("j_password", "password"); @@ -124,7 +124,7 @@ public class SessionManagementConfigServlet31Tests { Method method = mock(Method.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession(); - request.setRequestURI("/j_spring_security_check"); + request.setServletPath("/j_spring_security_check"); request.setMethod("POST"); request.setParameter("j_username", "user"); request.setParameter("j_password", "password"); diff --git a/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java b/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java index 56989a7c40..532df87ca3 100644 --- a/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java +++ b/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java @@ -30,9 +30,9 @@ public class MethodSecurityInterceptorWithAopConfigTests { static final String ACCESS_MANAGER_XML = "" + - " " + + " " + " " + - " " + + " " + ""; static final String TARGET_BEAN_AND_INTERCEPTOR = diff --git a/config/src/test/resources/org/springframework/security/util/filtertest-valid.xml b/config/src/test/resources/org/springframework/security/util/filtertest-valid.xml index 8ba04ee5d2..39d06dd9c0 100644 --- a/config/src/test/resources/org/springframework/security/util/filtertest-valid.xml +++ b/config/src/test/resources/org/springframework/security/util/filtertest-valid.xml @@ -104,7 +104,7 @@ - + diff --git a/core/src/main/java/org/springframework/security/access/ConfigAttributeEditor.java b/core/src/main/java/org/springframework/security/access/ConfigAttributeEditor.java deleted file mode 100644 index a92fb0f40b..0000000000 --- a/core/src/main/java/org/springframework/security/access/ConfigAttributeEditor.java +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.access; - -import org.springframework.util.StringUtils; - -import java.beans.PropertyEditorSupport; - -/** - * A property editor that can create a populated List<ConfigAttribute> from a comma separated list of values. - *

- * Trims preceding and trailing spaces from presented command separated tokens, as this can be a source - * of hard-to-spot configuration issues for end users. - * - * @author Ben Alex - * @deprecated - */ -public class ConfigAttributeEditor extends PropertyEditorSupport { - //~ Methods ======================================================================================================== - - public void setAsText(String s) throws IllegalArgumentException { - if (StringUtils.hasText(s)) { - setValue(SecurityConfig.createList(StringUtils.commaDelimitedListToStringArray(s))); - } else { - setValue(null); - } - } -} diff --git a/core/src/main/java/org/springframework/security/access/SecurityConfig.java b/core/src/main/java/org/springframework/security/access/SecurityConfig.java index 8f799a38ff..4ae6ecefc6 100644 --- a/core/src/main/java/org/springframework/security/access/SecurityConfig.java +++ b/core/src/main/java/org/springframework/security/access/SecurityConfig.java @@ -66,14 +66,6 @@ public class SecurityConfig implements ConfigAttribute { return createList(StringUtils.commaDelimitedListToStringArray(access)); } - /** - * @deprecated Use createList instead - */ - @Deprecated - public static List createSingleAttributeList(String access) { - return createList(access); - } - public static List createList(String... attributeNames) { Assert.notNull(attributeNames, "You must supply an array of attribute names"); List attributes = new ArrayList(attributeNames.length); diff --git a/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapper.java b/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapper.java deleted file mode 100755 index d4b18bc57d..0000000000 --- a/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.access.hierarchicalroles; - -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; - -/** - * This class wraps Spring Security's UserDetailsService in a way that its loadUserByUsername() - * method returns wrapped UserDetails that return all hierarchically reachable authorities - * instead of only the directly assigned authorities. - * - * @author Michael Mayr - * @deprecated use a {@code RoleHierarchyVoter} or use a {@code RoleHierarchyAuthoritiesMapper} to populate the - * Authentication object with the additional authorities. - */ -public class UserDetailsServiceWrapper implements UserDetailsService { - - private UserDetailsService userDetailsService = null; - - private RoleHierarchy roleHierarchy = null; - - public void setRoleHierarchy(RoleHierarchy roleHierarchy) { - this.roleHierarchy = roleHierarchy; - } - - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } - - public UserDetails loadUserByUsername(String username) { - UserDetails userDetails = userDetailsService.loadUserByUsername(username); - // wrapped UserDetailsService might throw UsernameNotFoundException or DataAccessException which will then bubble up - return new UserDetailsWrapper(userDetails, roleHierarchy); - } - - public UserDetailsService getWrappedUserDetailsService() { - return userDetailsService; - } - -} diff --git a/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsWrapper.java b/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsWrapper.java deleted file mode 100755 index 6d0c226d3d..0000000000 --- a/core/src/main/java/org/springframework/security/access/hierarchicalroles/UserDetailsWrapper.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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.access.hierarchicalroles; - -import java.util.Collection; - -import org.springframework.security.access.vote.RoleHierarchyVoter; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -/** - * This class wraps Spring Security's UserDetails in a way that its getAuthorities() method is - * delegated to RoleHierarchy.getReachableGrantedAuthorities. All other methods are - * delegated to the UserDetails implementation. - * - * @author Michael Mayr - * @deprecated use a {@link RoleHierarchyVoter} or {@code RoleHierarchyAuthoritiesMapper} instead. - */ -public class UserDetailsWrapper implements UserDetails { - - private static final long serialVersionUID = 1532428778390085311L; - - private UserDetails userDetails = null; - - private RoleHierarchy roleHierarchy = null; - - public UserDetailsWrapper(UserDetails userDetails, RoleHierarchy roleHierarchy) { - this.userDetails = userDetails; - this.roleHierarchy = roleHierarchy; - } - - public boolean isAccountNonExpired() { - return userDetails.isAccountNonExpired(); - } - - public boolean isAccountNonLocked() { - return userDetails.isAccountNonLocked(); - } - - public Collection getAuthorities() { - return roleHierarchy.getReachableGrantedAuthorities(userDetails.getAuthorities()); - } - - public boolean isCredentialsNonExpired() { - return userDetails.isCredentialsNonExpired(); - } - - public boolean isEnabled() { - return userDetails.isEnabled(); - } - - public String getPassword() { - return userDetails.getPassword(); - } - - public String getUsername() { - return userDetails.getUsername(); - } - - public UserDetails getUnwrappedUserDetails() { - return userDetails; - } - -} diff --git a/core/src/main/java/org/springframework/security/access/vote/AbstractAccessDecisionManager.java b/core/src/main/java/org/springframework/security/access/vote/AbstractAccessDecisionManager.java index ebe63115e9..4ad1bd05e6 100644 --- a/core/src/main/java/org/springframework/security/access/vote/AbstractAccessDecisionManager.java +++ b/core/src/main/java/org/springframework/security/access/vote/AbstractAccessDecisionManager.java @@ -50,9 +50,6 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan private boolean allowIfAllAbstainDecisions = false; - protected AbstractAccessDecisionManager() { - } - protected AbstractAccessDecisionManager(List> decisionVoters) { Assert.notEmpty(decisionVoters, "A list of AccessDecisionVoters is required"); this.decisionVoters = decisionVoters; @@ -84,24 +81,6 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions; } - /** - * @deprecated Use constructor - */ - @Deprecated - public void setDecisionVoters(List> newList) { - Assert.notEmpty(newList); - - Iterator> iter = newList.iterator(); - - while (iter.hasNext()) { - Object currentObject = iter.next(); - Assert.isInstanceOf(AccessDecisionVoter.class, currentObject, "AccessDecisionVoter " + - currentObject.getClass().getName() + " must implement AccessDecisionVoter"); - } - - this.decisionVoters = newList; - } - public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } diff --git a/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java b/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java index b4c9d0af38..b1699e796a 100644 --- a/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java +++ b/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java @@ -29,13 +29,6 @@ import org.springframework.security.core.Authentication; */ public class AffirmativeBased extends AbstractAccessDecisionManager { - /** - * @deprecated Use constructor which takes voter list - */ - @Deprecated - public AffirmativeBased() { - } - public AffirmativeBased(List> decisionVoters) { super(decisionVoters); } diff --git a/core/src/main/java/org/springframework/security/access/vote/ConsensusBased.java b/core/src/main/java/org/springframework/security/access/vote/ConsensusBased.java index 1be4e29731..716744fbbc 100644 --- a/core/src/main/java/org/springframework/security/access/vote/ConsensusBased.java +++ b/core/src/main/java/org/springframework/security/access/vote/ConsensusBased.java @@ -34,13 +34,6 @@ public class ConsensusBased extends AbstractAccessDecisionManager { private boolean allowIfEqualGrantedDeniedDecisions = true; - /** - * @deprecated Use constructor which takes voter list - */ - @Deprecated - public ConsensusBased() { - } - public ConsensusBased(List> decisionVoters) { super(decisionVoters); } diff --git a/core/src/main/java/org/springframework/security/access/vote/UnanimousBased.java b/core/src/main/java/org/springframework/security/access/vote/UnanimousBased.java index 9dd40c48cf..9485b43865 100644 --- a/core/src/main/java/org/springframework/security/access/vote/UnanimousBased.java +++ b/core/src/main/java/org/springframework/security/access/vote/UnanimousBased.java @@ -31,13 +31,6 @@ import org.springframework.security.core.Authentication; */ public class UnanimousBased extends AbstractAccessDecisionManager { - /** - * @deprecated Use constructor which takes voter list - */ - @Deprecated - public UnanimousBased() { - } - public UnanimousBased(List> decisionVoters) { super(decisionVoters); } diff --git a/core/src/main/java/org/springframework/security/authentication/AccountExpiredException.java b/core/src/main/java/org/springframework/security/authentication/AccountExpiredException.java index 8123b5080c..8d35698327 100644 --- a/core/src/main/java/org/springframework/security/authentication/AccountExpiredException.java +++ b/core/src/main/java/org/springframework/security/authentication/AccountExpiredException.java @@ -44,9 +44,4 @@ public class AccountExpiredException extends AccountStatusException { public AccountExpiredException(String msg, Throwable t) { super(msg, t); } - - @Deprecated - public AccountExpiredException(String msg, Object extraInformation) { - super(msg, extraInformation); - } } diff --git a/core/src/main/java/org/springframework/security/authentication/AccountStatusException.java b/core/src/main/java/org/springframework/security/authentication/AccountStatusException.java index 57c64b47be..cc4bff3f8f 100644 --- a/core/src/main/java/org/springframework/security/authentication/AccountStatusException.java +++ b/core/src/main/java/org/springframework/security/authentication/AccountStatusException.java @@ -16,9 +16,4 @@ public abstract class AccountStatusException extends AuthenticationException { public AccountStatusException(String msg, Throwable t) { super(msg, t); } - - @Deprecated - protected AccountStatusException(String msg, Object extraInformation) { - super(msg, extraInformation); - } } diff --git a/core/src/main/java/org/springframework/security/authentication/AccountStatusUserDetailsChecker.java b/core/src/main/java/org/springframework/security/authentication/AccountStatusUserDetailsChecker.java index 096751f478..ca3f3b391c 100644 --- a/core/src/main/java/org/springframework/security/authentication/AccountStatusUserDetailsChecker.java +++ b/core/src/main/java/org/springframework/security/authentication/AccountStatusUserDetailsChecker.java @@ -14,21 +14,21 @@ public class AccountStatusUserDetailsChecker implements UserDetailsChecker { public void check(UserDetails user) { if (!user.isAccountNonLocked()) { - throw new LockedException(messages.getMessage("AccountStatusUserDetailsChecker.locked", "User account is locked"), user); + throw new LockedException(messages.getMessage("AccountStatusUserDetailsChecker.locked", "User account is locked")); } if (!user.isEnabled()) { - throw new DisabledException(messages.getMessage("AccountStatusUserDetailsChecker.disabled", "User is disabled"), user); + throw new DisabledException(messages.getMessage("AccountStatusUserDetailsChecker.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { throw new AccountExpiredException(messages.getMessage("AccountStatusUserDetailsChecker.expired", - "User account has expired"), user); + "User account has expired")); } if (!user.isCredentialsNonExpired()) { throw new CredentialsExpiredException(messages.getMessage("AccountStatusUserDetailsChecker.credentialsExpired", - "User credentials have expired"), user); + "User credentials have expired")); } } } diff --git a/core/src/main/java/org/springframework/security/authentication/AnonymousAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/AnonymousAuthenticationProvider.java index b9bfde844b..995cebb02e 100644 --- a/core/src/main/java/org/springframework/security/authentication/AnonymousAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/authentication/AnonymousAuthenticationProvider.java @@ -33,31 +33,20 @@ import org.springframework.util.Assert; * * @author Ben Alex */ -public class AnonymousAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware { +public class AnonymousAuthenticationProvider implements AuthenticationProvider, MessageSourceAware { //~ Instance fields ================================================================================================ protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private String key; - /** - * - * @deprecated Use constructor injection - */ - @Deprecated - public AnonymousAuthenticationProvider() { - } - public AnonymousAuthenticationProvider(String key) { + Assert.hasLength(key, "A Key is required"); this.key = key; } //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { - Assert.hasLength(key, "A Key is required"); - } - public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { @@ -76,15 +65,6 @@ 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); diff --git a/core/src/main/java/org/springframework/security/authentication/AuthenticationDetails.java b/core/src/main/java/org/springframework/security/authentication/AuthenticationDetails.java deleted file mode 100755 index cb6a44fbd3..0000000000 --- a/core/src/main/java/org/springframework/security/authentication/AuthenticationDetails.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.springframework.security.authentication; - -import org.springframework.security.core.SpringSecurityCoreVersion; - -import java.io.Serializable; - -/** -* A holder of the context as a string. -* -* @author Ruud Senden -* @since 2.0 -*/ -@Deprecated -public class AuthenticationDetails implements Serializable { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - //~ Instance fields ================================================================================================ - - private final String context; - - //~ Constructors =================================================================================================== - - /** - * Constructor. - * - * @param context that the authentication request is initiated from - */ - public AuthenticationDetails(Object context) { - this.context = context == null ? "" : context.toString(); - doPopulateAdditionalInformation(context); - } - - //~ Methods ======================================================================================================== - - /** - * Provided so that subclasses can populate additional information. - * - * @param context the existing contextual information - */ - protected void doPopulateAdditionalInformation(Object context) {} - - public boolean equals(Object obj) { - if (obj instanceof AuthenticationDetails) { - AuthenticationDetails rhs = (AuthenticationDetails) obj; - - // this.context cannot be null - if (!context.equals(rhs.getContext())) { - return false; - } - - return true; - } - - return false; - } - - /** - * Indicates the context. - * - * @return the context - */ - public String getContext() { - return context; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(super.toString() + ": "); - sb.append("Context: " + this.getContext()); - - return sb.toString(); - } -} diff --git a/core/src/main/java/org/springframework/security/authentication/AuthenticationDetailsSourceImpl.java b/core/src/main/java/org/springframework/security/authentication/AuthenticationDetailsSourceImpl.java deleted file mode 100755 index 0d774b6266..0000000000 --- a/core/src/main/java/org/springframework/security/authentication/AuthenticationDetailsSourceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.springframework.security.authentication; - -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; - -import java.lang.reflect.Constructor; - -/** - * Base implementation of {@link AuthenticationDetailsSource}. - *

- * By default will create an instance of AuthenticationDetails. - * Any object that accepts an Object as its sole constructor can - * be used instead of this default. - *

- * - * @author Ruud Senden - * @since 2.0 - * @deprecated Write an implementation of AuthenticationDetailsSource which returns the desired type directly. - */ -@Deprecated -public class AuthenticationDetailsSourceImpl implements AuthenticationDetailsSource { - //~ Instance fields ================================================================================================ - - private Class clazz = AuthenticationDetails.class; - - //~ Methods ======================================================================================================== - - public Object buildDetails(Object context) { - Object result = null; - try { - Constructor constructor = getFirstMatchingConstructor(context); - result = constructor.newInstance(context); - } catch (Exception ex) { - ReflectionUtils.handleReflectionException(ex); - } - - return result; - } - - /** - * Return the first matching constructor that can take the given object - * as an argument. Please note that we cannot use - * getDeclaredConstructor(new Class[]{object.getClass()}) - * as this will only match if the constructor argument type matches - * the object type exactly (instead of checking whether it is assignable) - * - * @param object the object for which to find a matching constructor - * @return a matching constructor for the given object - * @throws NoSuchMethodException if no matching constructor can be found - */ - private Constructor getFirstMatchingConstructor(Object object) throws NoSuchMethodException { - Constructor[] constructors = clazz.getDeclaredConstructors(); - Constructor constructor = null; - for (Constructor tryMe : constructors) { - Class[] parameterTypes = tryMe.getParameterTypes(); - if (parameterTypes.length == 1 && (object == null || parameterTypes[0].isInstance(object))) { - constructor = tryMe; - break; - } - } - - if (constructor == null) { - if (object == null) { - throw new NoSuchMethodException("No constructor found that can take a single argument"); - } else { - throw new NoSuchMethodException("No constructor found that can take a single argument of type " + object.getClass()); - } - } - return constructor; - } - - public void setClazz(Class clazz) { - Assert.notNull(clazz, "Class required"); - this.clazz = clazz; - } -} diff --git a/core/src/main/java/org/springframework/security/authentication/BadCredentialsException.java b/core/src/main/java/org/springframework/security/authentication/BadCredentialsException.java index 9543a90e69..7bfca4bffa 100644 --- a/core/src/main/java/org/springframework/security/authentication/BadCredentialsException.java +++ b/core/src/main/java/org/springframework/security/authentication/BadCredentialsException.java @@ -36,11 +36,6 @@ public class BadCredentialsException extends AuthenticationException { super(msg); } - @Deprecated - public BadCredentialsException(String msg, Object extraInformation) { - super(msg, extraInformation); - } - /** * Constructs a BadCredentialsException with the specified * message and root cause. diff --git a/core/src/main/java/org/springframework/security/authentication/CredentialsExpiredException.java b/core/src/main/java/org/springframework/security/authentication/CredentialsExpiredException.java index cbd90fa616..74f5dca95e 100644 --- a/core/src/main/java/org/springframework/security/authentication/CredentialsExpiredException.java +++ b/core/src/main/java/org/springframework/security/authentication/CredentialsExpiredException.java @@ -44,9 +44,4 @@ public class CredentialsExpiredException extends AccountStatusException { public CredentialsExpiredException(String msg, Throwable t) { super(msg, t); } - - @Deprecated - public CredentialsExpiredException(String msg, Object extraInformation) { - super(msg, extraInformation); - } } diff --git a/core/src/main/java/org/springframework/security/authentication/DisabledException.java b/core/src/main/java/org/springframework/security/authentication/DisabledException.java index 2f423ada32..06fae8e8d9 100644 --- a/core/src/main/java/org/springframework/security/authentication/DisabledException.java +++ b/core/src/main/java/org/springframework/security/authentication/DisabledException.java @@ -43,9 +43,4 @@ public class DisabledException extends AccountStatusException { public DisabledException(String msg, Throwable t) { super(msg, t); } - - @Deprecated - public DisabledException(String msg, Object extraInformation) { - super(msg, extraInformation); - } } diff --git a/core/src/main/java/org/springframework/security/authentication/LockedException.java b/core/src/main/java/org/springframework/security/authentication/LockedException.java index 9db269ece6..fa102cb5aa 100644 --- a/core/src/main/java/org/springframework/security/authentication/LockedException.java +++ b/core/src/main/java/org/springframework/security/authentication/LockedException.java @@ -44,9 +44,4 @@ public class LockedException extends AccountStatusException { public LockedException(String msg, Throwable t) { super(msg, t); } - - @Deprecated - public LockedException(String msg, Object extraInformation) { - super(msg, extraInformation); - } } diff --git a/core/src/main/java/org/springframework/security/authentication/ProviderManager.java b/core/src/main/java/org/springframework/security/authentication/ProviderManager.java index 41b3b3f850..6cbea8c4d2 100644 --- a/core/src/main/java/org/springframework/security/authentication/ProviderManager.java +++ b/core/src/main/java/org/springframework/security/authentication/ProviderManager.java @@ -86,14 +86,6 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private AuthenticationManager parent; private boolean eraseCredentialsAfterAuthentication = true; - private boolean clearExtraInformation = false; - - /** - * @deprecated Use constructor which takes provider list - */ - @Deprecated - public ProviderManager() { - } public ProviderManager(List providers) { this(providers, null); @@ -208,11 +200,6 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar @SuppressWarnings("deprecation") private void prepareException(AuthenticationException ex, Authentication auth) { eventPublisher.publishAuthenticationFailure(ex, auth); - ex.setAuthentication(auth); - - if (clearExtraInformation) { - ex.clearExtraInformation(); - } } /** @@ -238,14 +225,6 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar this.messages = new MessageSourceAccessor(messageSource); } - /** - * @deprecated Use constructor injection - */ - @Deprecated - public void setParent(AuthenticationManager parent) { - this.parent = parent; - } - public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null"); this.eventPublisher = eventPublisher; @@ -267,39 +246,6 @@ public class ProviderManager implements AuthenticationManager, MessageSourceAwar return eraseCredentialsAfterAuthentication; } - /** - * Sets the {@link AuthenticationProvider} objects to be used for authentication. - * - * @param providers the list of authentication providers which will be used to process authentication requests. - * - * @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", "rawtypes" }) - public void setProviders(List providers) { - Assert.notNull(providers, "Providers list cannot be null"); - for(Object currentObject : providers) { - Assert.isInstanceOf(AuthenticationProvider.class, currentObject, "Can only provide AuthenticationProvider instances"); - } - - this.providers = providers; - } - - /** - * If set to true, the {@code extraInformation} set on an {@code AuthenticationException} will be cleared - * before rethrowing it. This is useful for use with remoting protocols where the information shouldn't - * be serialized to the client. Defaults to 'false'. - * - * @see org.springframework.security.core.AuthenticationException#getExtraInformation() - * @deprecated the {@code extraInformation} property is deprecated - */ - @Deprecated - public void setClearExtraInformation(boolean clearExtraInformation) { - this.clearExtraInformation = clearExtraInformation; - } - private static final class NullEventPublisher implements AuthenticationEventPublisher { public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) {} public void publishAuthenticationSuccess(Authentication authentication) {} diff --git a/core/src/main/java/org/springframework/security/authentication/RememberMeAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/RememberMeAuthenticationProvider.java index e412ba470e..9714712d44 100644 --- a/core/src/main/java/org/springframework/security/authentication/RememberMeAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/authentication/RememberMeAuthenticationProvider.java @@ -37,21 +37,15 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider, protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private String key; - /** - * @deprecated Use constructor injection - */ - @Deprecated - public RememberMeAuthenticationProvider() { - } public RememberMeAuthenticationProvider(String key) { + Assert.hasLength(key); this.key = key; } //~ Methods ======================================================================================================== public void afterPropertiesSet() throws Exception { - Assert.hasLength(key); Assert.notNull(this.messages, "A message source must be set"); } @@ -72,15 +66,6 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider, return key; } - /** - * - * @deprecated Use constructor injection - */ - @Deprecated - public void setKey(String key) { - this.key = key; - } - public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } diff --git a/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java index 62dbda675f..051565762f 100644 --- a/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.java @@ -308,21 +308,21 @@ public abstract class AbstractUserDetailsAuthenticationProvider implements Authe logger.debug("User account is locked"); throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", - "User account is locked"), user); + "User account is locked")); } if (!user.isEnabled()) { logger.debug("User account is disabled"); throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", - "User is disabled"), user); + "User is disabled")); } if (!user.isAccountNonExpired()) { logger.debug("User account is expired"); throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", - "User account has expired"), user); + "User account has expired")); } } } @@ -334,7 +334,7 @@ public abstract class AbstractUserDetailsAuthenticationProvider implements Authe throw new CredentialsExpiredException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.credentialsExpired", - "User credentials have expired"), user); + "User credentials have expired")); } } } diff --git a/core/src/main/java/org/springframework/security/authentication/dao/DaoAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/dao/DaoAuthenticationProvider.java index 8c34cc4197..8e2eb76303 100644 --- a/core/src/main/java/org/springframework/security/authentication/dao/DaoAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/authentication/dao/DaoAuthenticationProvider.java @@ -77,7 +77,7 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); + "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials().toString(); @@ -86,7 +86,7 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); + "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } } diff --git a/core/src/main/java/org/springframework/security/context/DelegatingApplicationListener.java b/core/src/main/java/org/springframework/security/context/DelegatingApplicationListener.java index 517808f4d2..fa6ab215ac 100644 --- a/core/src/main/java/org/springframework/security/context/DelegatingApplicationListener.java +++ b/core/src/main/java/org/springframework/security/context/DelegatingApplicationListener.java @@ -32,7 +32,6 @@ import java.util.List; public final class DelegatingApplicationListener implements ApplicationListener { private List listeners = new ArrayList(); - @Override public void onApplicationEvent(ApplicationEvent event) { if(event == null) { return; diff --git a/core/src/main/java/org/springframework/security/core/AuthenticationException.java b/core/src/main/java/org/springframework/security/core/AuthenticationException.java index 8a14b4d37c..74f27234a2 100644 --- a/core/src/main/java/org/springframework/security/core/AuthenticationException.java +++ b/core/src/main/java/org/springframework/security/core/AuthenticationException.java @@ -22,10 +22,6 @@ package org.springframework.security.core; * @author Ben Alex */ public abstract class AuthenticationException extends RuntimeException { - //~ Instance fields ================================================================================================ - - private Authentication authentication; - private transient Object extraInformation; //~ Constructors =================================================================================================== @@ -48,47 +44,4 @@ public abstract class AuthenticationException extends RuntimeException { super(msg); } - /** - * @deprecated Use the exception message or use a custom exception if you really need additional information. - */ - @Deprecated - public AuthenticationException(String msg, Object extraInformation) { - super(msg); - if (extraInformation instanceof CredentialsContainer) { - ((CredentialsContainer) extraInformation).eraseCredentials(); - } - this.extraInformation = extraInformation; - } - - //~ Methods ======================================================================================================== - - /** - * The authentication request which this exception corresponds to (may be {@code null}) - * @deprecated to avoid potential leaking of sensitive information (e.g. through serialization/remoting). - */ - @Deprecated - public Authentication getAuthentication() { - return authentication; - } - - @Deprecated - public void setAuthentication(Authentication authentication) { - this.authentication = authentication; - } - - /** - * Any additional information about the exception. Generally a {@code UserDetails} object. - * - * @return extra information or {@code null} - * @deprecated Use the exception message or use a custom exception if you really need additional information. - */ - @Deprecated - public Object getExtraInformation() { - return extraInformation; - } - - @Deprecated - public void clearExtraInformation() { - this.extraInformation = null; - } } diff --git a/core/src/main/java/org/springframework/security/core/authority/GrantedAuthoritiesContainerImpl.java b/core/src/main/java/org/springframework/security/core/authority/GrantedAuthoritiesContainerImpl.java deleted file mode 100644 index 2cfc281738..0000000000 --- a/core/src/main/java/org/springframework/security/core/authority/GrantedAuthoritiesContainerImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.springframework.security.core.authority; - -import java.util.*; - -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.SpringSecurityCoreVersion; -import org.springframework.util.Assert; - -@Deprecated -public class GrantedAuthoritiesContainerImpl implements MutableGrantedAuthoritiesContainer { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - private List authorities; - - public void setGrantedAuthorities(Collection newAuthorities) { - ArrayList temp = new ArrayList(newAuthorities.size()); - temp.addAll(newAuthorities); - authorities = Collections.unmodifiableList(temp); - } - - public List getGrantedAuthorities() { - Assert.notNull(authorities, "Granted authorities have not been set"); - return authorities; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Authorities: ").append(authorities); - return sb.toString(); - } -} diff --git a/core/src/main/java/org/springframework/security/core/authority/GrantedAuthorityImpl.java b/core/src/main/java/org/springframework/security/core/authority/GrantedAuthorityImpl.java deleted file mode 100644 index 30cf605642..0000000000 --- a/core/src/main/java/org/springframework/security/core/authority/GrantedAuthorityImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.authority; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.SpringSecurityCoreVersion; -import org.springframework.util.Assert; - - -/** - * Basic concrete implementation of a {@link GrantedAuthority}. - * - *

- * Stores a String representation of an authority granted to the {@link Authentication} object. - * - * @author Ben Alex - * @deprecated Use the final class {@link SimpleGrantedAuthority} or implement your own. - */ -@Deprecated -public class GrantedAuthorityImpl implements GrantedAuthority { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - //~ Instance fields ================================================================================================ - - private final String role; - - //~ Constructors =================================================================================================== - - public GrantedAuthorityImpl(String role) { - Assert.hasText(role, "A granted authority textual representation is required"); - this.role = role; - } - - //~ Methods ======================================================================================================== - - public boolean equals(Object obj) { - if (obj instanceof String) { - return obj.equals(this.role); - } - - if (obj instanceof GrantedAuthority) { - GrantedAuthority attr = (GrantedAuthority) obj; - - return this.role.equals(attr.getAuthority()); - } - - return false; - } - - public String getAuthority() { - return this.role; - } - - public int hashCode() { - return this.role.hashCode(); - } - - public String toString() { - return this.role; - } -} diff --git a/core/src/main/java/org/springframework/security/core/authority/MutableGrantedAuthoritiesContainer.java b/core/src/main/java/org/springframework/security/core/authority/MutableGrantedAuthoritiesContainer.java deleted file mode 100644 index c9906ef691..0000000000 --- a/core/src/main/java/org/springframework/security/core/authority/MutableGrantedAuthoritiesContainer.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.springframework.security.core.authority; - -import org.springframework.security.core.GrantedAuthority; - -import java.util.*; - -/** - * Indicates that a object can be used to store and retrieve GrantedAuthority objects. - *

- * Typically used in a pre-authenticated scenario when an AuthenticationDetails instance may also be - * used to obtain user authorities. - * - * @author Ruud Senden - * @author Luke Taylor - * @since 2.0 - */ -@Deprecated -public interface MutableGrantedAuthoritiesContainer extends GrantedAuthoritiesContainer { - /** - * Used to store authorities in the containing object. - */ - void setGrantedAuthorities(Collection authorities); -} diff --git a/core/src/main/java/org/springframework/security/core/session/SessionIdentifierAware.java b/core/src/main/java/org/springframework/security/core/session/SessionIdentifierAware.java deleted file mode 100644 index 18ed0ac548..0000000000 --- a/core/src/main/java/org/springframework/security/core/session/SessionIdentifierAware.java +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.session; - -/** - * Implemented by {@link org.springframework.security.core.Authentication#getDetails()} - * implementations that are capable of returning a session ID. - *

- * Used to extract the session ID from an Authentication object. - * - * @author Ben Alex - * @deprecated Legacy of former concurrency control implementation. Will be removed in a future version. - */ -@Deprecated -public interface SessionIdentifierAware { - //~ Methods ======================================================================================================== - - /** - * Obtains the session ID. - * - * @return the session ID, or null if not known. - */ - String getSessionId(); -} diff --git a/core/src/main/java/org/springframework/security/core/userdetails/UsernameNotFoundException.java b/core/src/main/java/org/springframework/security/core/userdetails/UsernameNotFoundException.java index b2fd117994..547d9402ff 100644 --- a/core/src/main/java/org/springframework/security/core/userdetails/UsernameNotFoundException.java +++ b/core/src/main/java/org/springframework/security/core/userdetails/UsernameNotFoundException.java @@ -36,18 +36,6 @@ public class UsernameNotFoundException extends AuthenticationException { super(msg); } - /** - * Constructs a {@code UsernameNotFoundException}, making use of the {@code extraInformation} - * property of the superclass. - * - * @param msg the detail message - * @param extraInformation additional information such as the username. - */ - @Deprecated - public UsernameNotFoundException(String msg, Object extraInformation) { - super(msg, extraInformation); - } - /** * Constructs a {@code UsernameNotFoundException} with the specified message and root cause. * diff --git a/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java b/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java index aff4939e5e..2e9eef98f2 100644 --- a/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java +++ b/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java @@ -154,7 +154,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { logger.debug("Query returned no results for user '" + username + "'"); throw new UsernameNotFoundException( - messages.getMessage("JdbcDaoImpl.notFound", new Object[]{username}, "Username {0} not found"), username); + messages.getMessage("JdbcDaoImpl.notFound", new Object[]{username}, "Username {0} not found")); } UserDetails user = users.get(0); // contains no GrantedAuthority[] @@ -178,7 +178,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { throw new UsernameNotFoundException( messages.getMessage("JdbcDaoImpl.noAuthority", - new Object[] {username}, "User {0} has no GrantedAuthority"), username); + new Object[] {username}, "User {0} has no GrantedAuthority")); } return createUserDetails(username, user, dbAuths); diff --git a/core/src/main/java/org/springframework/security/core/userdetails/memory/InMemoryDaoImpl.java b/core/src/main/java/org/springframework/security/core/userdetails/memory/InMemoryDaoImpl.java deleted file mode 100644 index b4a8ad3ed4..0000000000 --- a/core/src/main/java/org/springframework/security/core/userdetails/memory/InMemoryDaoImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.userdetails.memory; - -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - -import org.springframework.beans.factory.InitializingBean; - -import org.springframework.util.Assert; - -import java.util.Properties; - - -/** - * Retrieves user details from an in-memory list created by the bean context. - * - * @author Ben Alex - * @deprecated Use InMemoryUserDetailsManager instead (or write your own implementation) - */ -@Deprecated -public class InMemoryDaoImpl implements UserDetailsService, InitializingBean { - //~ Instance fields ================================================================================================ - - private UserMap userMap; - - //~ Methods ======================================================================================================== - - public void afterPropertiesSet() throws Exception { - Assert.notNull(this.userMap, - "A list of users, passwords, enabled/disabled status and their granted authorities must be set"); - } - - public UserMap getUserMap() { - return userMap; - } - - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - return userMap.getUser(username); - } - - public void setUserMap(UserMap userMap) { - this.userMap = userMap; - } - - /** - * Modifies the internal UserMap to reflect the Properties instance passed. This - * helps externalise user information to another file etc. - * - * @param props the account information in a Properties object format - */ - public void setUserProperties(Properties props) { - UserMap userMap = new UserMap(); - this.userMap = UserMapEditor.addUsersFromProperties(userMap, props); - } -} diff --git a/core/src/main/java/org/springframework/security/core/userdetails/memory/UserMap.java b/core/src/main/java/org/springframework/security/core/userdetails/memory/UserMap.java deleted file mode 100644 index 77092e3c57..0000000000 --- a/core/src/main/java/org/springframework/security/core/userdetails/memory/UserMap.java +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.userdetails.memory; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.util.Assert; - - -/** - * Used by {@link InMemoryDaoImpl} to store a list of users and their corresponding granted authorities. - *

- * Usernames are used as the lookup key and are stored in lower case, to allow case-insensitive lookups. So this class - * should not be used if usernames need to be case-sensitive. - * - * @author Ben Alex - * @deprecated Use a plain map instead - */ -@Deprecated -public class UserMap { - //~ Static fields/initializers ===================================================================================== - - private static final Log logger = LogFactory.getLog(UserMap.class); - - //~ Instance fields ================================================================================================ - - private final Map userMap = new HashMap(); - - //~ Methods ======================================================================================================== - - /** - * Adds a user to the in-memory map. - * - * @param user the user to be stored - * - * @throws IllegalArgumentException if a null User was passed - */ - public void addUser(UserDetails user) throws IllegalArgumentException { - Assert.notNull(user, "Must be a valid User"); - - logger.info("Adding user [" + user + "]"); - this.userMap.put(user.getUsername().toLowerCase(), user); - } - - /** - * Locates the specified user by performing a case insensitive search by username. - * - * @param username to find - * - * @return the located user - * - * @throws UsernameNotFoundException if the user could not be found - */ - public UserDetails getUser(String username) throws UsernameNotFoundException { - UserDetails result = this.userMap.get(username.toLowerCase()); - - if (result == null) { - throw new UsernameNotFoundException("Could not find user: " + username, username); - } - - return result; - } - - /** - * Indicates the size of the user map. - * - * @return the number of users in the map - */ - public int getUserCount() { - return this.userMap.size(); - } - - /** - * Set the users in this {@link UserMap}. Overrides previously added users. - * - * @param users {@link Map} <{@link String}, {@link UserDetails}> with pairs (username, userdetails) - * @since 1.1 - */ - public void setUsers(Map users) { - userMap.clear(); - for (Map.Entry entry : users.entrySet()) { - userMap.put(entry.getKey().toLowerCase(), entry.getValue()); - } - } -} diff --git a/core/src/main/java/org/springframework/security/core/userdetails/memory/UserMapEditor.java b/core/src/main/java/org/springframework/security/core/userdetails/memory/UserMapEditor.java deleted file mode 100644 index 25c42b31e0..0000000000 --- a/core/src/main/java/org/springframework/security/core/userdetails/memory/UserMapEditor.java +++ /dev/null @@ -1,88 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.userdetails.memory; - -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; - -import org.springframework.beans.propertyeditors.PropertiesEditor; - -import java.beans.PropertyEditorSupport; - -import java.util.Iterator; -import java.util.Properties; - - -/** - * Property editor to assist with the setup of a {@link UserMap}.

The format of entries should be:

- *

username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]

- *

The password must always be the first entry after the equals. The enabled or - * disabled keyword can appear anywhere (apart from the first entry reserved for the password). If - * neither enabled or disabled appear, the default is enabled. At least one - * granted authority must be listed.

- *

The username represents the key and duplicates are handled the same was as duplicates would be - * in Java Properties files.

- *

If the above requirements are not met, the invalid entry will be silently ignored.

- *

This editor always assumes each entry has a non-expired account and non-expired credentials. However, it - * does honour the user enabled/disabled flag as described above.

- * - * @author Ben Alex - */ -@Deprecated -public class UserMapEditor extends PropertyEditorSupport { - //~ Methods ======================================================================================================== - - public static UserMap addUsersFromProperties(UserMap userMap, Properties props) { - // Now we have properties, process each one individually - UserAttributeEditor configAttribEd = new UserAttributeEditor(); - - for (Object o : props.keySet()) { - String username = (String) o; - String value = props.getProperty(username); - - // Convert value to a password, enabled setting, and list of granted authorities - configAttribEd.setAsText(value); - - UserAttribute attr = (UserAttribute) configAttribEd.getValue(); - - // Make a user object, assuming the properties were properly provided - if (attr != null) { - UserDetails user = new User(username, attr.getPassword(), attr.isEnabled(), true, true, true, - attr.getAuthorities()); - userMap.addUser(user); - } - } - - return userMap; - } - - public void setAsText(String s) throws IllegalArgumentException { - UserMap userMap = new UserMap(); - - if ((s == null) || "".equals(s)) { - // Leave value in property editor null - } else { - // Use properties editor to tokenize the string - PropertiesEditor propertiesEditor = new PropertiesEditor(); - propertiesEditor.setAsText(s); - - Properties props = (Properties) propertiesEditor.getValue(); - addUsersFromProperties(userMap, props); - } - - setValue(userMap); - } -} diff --git a/core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapperTests.java b/core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapperTests.java deleted file mode 100755 index b337230416..0000000000 --- a/core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapperTests.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.springframework.security.access.hierarchicalroles; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - -@SuppressWarnings("deprecation") -public class UserDetailsServiceWrapperTests { - - private UserDetailsService wrappedUserDetailsService = null; - private UserDetailsServiceWrapper userDetailsServiceWrapper = null; - - @Before - public void setUp() throws Exception { - RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); - roleHierarchy.setHierarchy("ROLE_A > ROLE_B"); - final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_A")); - final UserDetailsService wrappedUserDetailsService = mock(UserDetailsService.class); - when(wrappedUserDetailsService.loadUserByUsername("EXISTING_USER")).thenReturn(user); - when(wrappedUserDetailsService.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION")).thenThrow(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION")); - - this.wrappedUserDetailsService = wrappedUserDetailsService; - userDetailsServiceWrapper = new UserDetailsServiceWrapper(); - userDetailsServiceWrapper.setRoleHierarchy(roleHierarchy); - userDetailsServiceWrapper.setUserDetailsService(wrappedUserDetailsService); - } - - @Test - public void testLoadUserByUsername() { - UserDetails expectedUserDetails = new User("EXISTING_USER", "PASSWORD", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); - UserDetails userDetails = userDetailsServiceWrapper.loadUserByUsername("EXISTING_USER"); - assertEquals(expectedUserDetails.getPassword(), userDetails.getPassword()); - assertEquals(expectedUserDetails.getUsername(), userDetails.getUsername()); - assertEquals(expectedUserDetails.isAccountNonExpired(), userDetails.isAccountNonExpired()); - assertEquals(expectedUserDetails.isAccountNonLocked(), userDetails.isAccountNonLocked()); - assertEquals(expectedUserDetails.isCredentialsNonExpired(), expectedUserDetails.isCredentialsNonExpired()); - assertEquals(expectedUserDetails.isEnabled(), userDetails.isEnabled()); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(expectedUserDetails.getAuthorities(), userDetails.getAuthorities())); - - try { - userDetails = userDetailsServiceWrapper.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"); - fail("testLoadUserByUsername() - UsernameNotFoundException did not bubble up!"); - } catch (UsernameNotFoundException e) {} - } - - @Test - public void testGetWrappedUserDetailsService() { - assertTrue(userDetailsServiceWrapper.getWrappedUserDetailsService() == wrappedUserDetailsService); - } -} diff --git a/core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsWrapperTests.java b/core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsWrapperTests.java deleted file mode 100755 index 8fa86d64fb..0000000000 --- a/core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsWrapperTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.springframework.security.access.hierarchicalroles; - -import junit.framework.TestCase; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; - -import java.util.*; - -/** - * Tests for {@link UserDetailsWrapper}. - * - * @author Michael Mayr - */ -@SuppressWarnings({"deprecation"}) -public class UserDetailsWrapperTests extends TestCase { - - private List authorities = null; - private UserDetails userDetails1 = null; - private UserDetails userDetails2 = null; - private UserDetailsWrapper userDetailsWrapper1 = null; - private UserDetailsWrapper userDetailsWrapper2 = null; - - protected void setUp() throws Exception { - RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); - roleHierarchy.setHierarchy("ROLE_A > ROLE_B"); - authorities = AuthorityUtils.createAuthorityList("ROLE_A"); - userDetails1 = new User("TestUser1", "TestPassword1", true, true, true, true, authorities); - userDetails2 = new User("TestUser2", "TestPassword2", false, false, false, false, authorities); - userDetailsWrapper1 = new UserDetailsWrapper(userDetails1, roleHierarchy); - userDetailsWrapper2 = new UserDetailsWrapper(userDetails2, roleHierarchy); - } - - public void testIsAccountNonExpired() { - assertEquals(userDetails1.isAccountNonExpired(), userDetailsWrapper1.isAccountNonExpired()); - assertEquals(userDetails2.isAccountNonExpired(), userDetailsWrapper2.isAccountNonExpired()); - } - - public void testIsAccountNonLocked() { - assertEquals(userDetails1.isAccountNonLocked(), userDetailsWrapper1.isAccountNonLocked()); - assertEquals(userDetails2.isAccountNonLocked(), userDetailsWrapper2.isAccountNonLocked()); - } - - public void testGetAuthorities() { - List expectedAuthorities = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(userDetailsWrapper1.getAuthorities(), expectedAuthorities)); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(userDetailsWrapper2.getAuthorities(), expectedAuthorities)); - } - - public void testIsCredentialsNonExpired() { - assertEquals(userDetails1.isCredentialsNonExpired(), userDetailsWrapper1.isCredentialsNonExpired()); - assertEquals(userDetails2.isCredentialsNonExpired(), userDetailsWrapper2.isCredentialsNonExpired()); - } - - public void testIsEnabled() { - assertEquals(userDetails1.isEnabled(), userDetailsWrapper1.isEnabled()); - assertEquals(userDetails2.isEnabled(), userDetailsWrapper2.isEnabled()); - } - - public void testGetPassword() { - assertEquals(userDetails1.getPassword(), userDetailsWrapper1.getPassword()); - assertEquals(userDetails2.getPassword(), userDetailsWrapper2.getPassword()); - } - - public void testGetUsername() { - assertEquals(userDetails1.getUsername(), userDetailsWrapper1.getUsername()); - assertEquals(userDetails2.getUsername(), userDetailsWrapper2.getUsername()); - } - - public void testGetUnwrappedUserDetails() { - assertTrue(userDetailsWrapper1.getUnwrappedUserDetails() == userDetails1); - assertTrue(userDetailsWrapper2.getUnwrappedUserDetails() == userDetails2); - } - -} diff --git a/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java b/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java index 25857ad7d1..3224ff0c7d 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java @@ -41,31 +41,34 @@ public class AbstractAccessDecisionManagerTests extends TestCase { //~ Methods ======================================================================================================== public void testAllowIfAccessDecisionManagerDefaults() { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); + List list = new Vector(); + DenyAgainVoter denyVoter = new DenyAgainVoter(); + list.add(denyVoter); + MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); assertTrue(!mock.isAllowIfAllAbstainDecisions()); // default mock.setAllowIfAllAbstainDecisions(true); assertTrue(mock.isAllowIfAllAbstainDecisions()); // changed } public void testDelegatesSupportsClassRequests() throws Exception { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); List list = new Vector(); list.add(new DenyVoter()); list.add(new MockStringOnlyVoter()); - mock.setDecisionVoters(list); + + MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); assertTrue(mock.supports(String.class)); assertTrue(!mock.supports(Integer.class)); } public void testDelegatesSupportsRequests() throws Exception { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); List list = new Vector(); DenyVoter voter = new DenyVoter(); DenyAgainVoter denyVoter = new DenyAgainVoter(); list.add(voter); list.add(denyVoter); - mock.setDecisionVoters(list); + + MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); ConfigAttribute attr = new SecurityConfig("DENY_AGAIN_FOR_SURE"); assertTrue(mock.supports(attr)); @@ -75,40 +78,20 @@ public class AbstractAccessDecisionManagerTests extends TestCase { } public void testProperlyStoresListOfVoters() throws Exception { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); List list = new Vector(); DenyVoter voter = new DenyVoter(); DenyAgainVoter denyVoter = new DenyAgainVoter(); list.add(voter); list.add(denyVoter); - mock.setDecisionVoters(list); + MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); assertEquals(list.size(), mock.getDecisionVoters().size()); } public void testRejectsEmptyList() throws Exception { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); List list = new Vector(); try { - mock.setDecisionVoters(list); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } - } - - public void testRejectsListContainingInvalidObjectTypes() { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); - List list = new Vector(); - DenyVoter voter = new DenyVoter(); - DenyAgainVoter denyVoter = new DenyAgainVoter(); - String notAVoter = "NOT_A_VOTER"; - list.add(voter); - list.add(notAVoter); - list.add(denyVoter); - - try { - mock.setDecisionVoters(list); + new MockDecisionManagerImpl(list); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -116,10 +99,8 @@ public class AbstractAccessDecisionManagerTests extends TestCase { } public void testRejectsNullVotersList() throws Exception { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); - try { - mock.setDecisionVoters(null); + new MockDecisionManagerImpl(null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -133,10 +114,8 @@ public class AbstractAccessDecisionManagerTests extends TestCase { public void testWillNotStartIfDecisionVotersNotSet() throws Exception { - MockDecisionManagerImpl mock = new MockDecisionManagerImpl(); - try { - mock.afterPropertiesSet(); + new MockDecisionManagerImpl(null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -146,6 +125,10 @@ public class AbstractAccessDecisionManagerTests extends TestCase { //~ Inner Classes ================================================================================================== private class MockDecisionManagerImpl extends AbstractAccessDecisionManager { + protected MockDecisionManagerImpl(List> decisionVoters) { + super(decisionVoters); + } + public void decide(Authentication authentication, Object object, Collection configAttributes) { } } diff --git a/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java b/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java index 4bfc424594..680b60b306 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java @@ -48,7 +48,6 @@ public class AffirmativeBasedTests { @Before @SuppressWarnings("unchecked") public void setup() { - mgr = new AffirmativeBased(); grant = mock(AccessDecisionVoter.class); abstain = mock(AccessDecisionVoter.class); @@ -61,32 +60,33 @@ public class AffirmativeBasedTests { @Test public void oneAffirmativeVoteOneDenyVoteOneAbstainVoteGrantsAccess() throws Exception { - mgr.setDecisionVoters(Arrays.>asList(grant, deny, abstain)); + + mgr = new AffirmativeBased(Arrays.>asList(grant, deny, abstain)); mgr.afterPropertiesSet(); mgr.decide(user, new Object(), attrs); } @Test public void oneDenyVoteOneAbstainVoteOneAffirmativeVoteGrantsAccess() throws Exception { - mgr.setDecisionVoters(Arrays.>asList(deny, abstain, grant)); + mgr = new AffirmativeBased(Arrays.>asList(deny, abstain, grant)); mgr.decide(user, new Object(), attrs); } @Test public void oneAffirmativeVoteTwoAbstainVotesGrantsAccess() throws Exception { - mgr.setDecisionVoters(Arrays.>asList(grant, abstain, abstain)); + mgr = new AffirmativeBased(Arrays.>asList(grant, abstain, abstain)); mgr.decide(user, new Object(), attrs); } @Test(expected=AccessDeniedException.class) public void oneDenyVoteTwoAbstainVotesDeniesAccess() throws Exception { - mgr.setDecisionVoters(Arrays.>asList(deny, abstain, abstain)); + mgr = new AffirmativeBased(Arrays.>asList(deny, abstain, abstain)); mgr.decide(user, new Object(), attrs); } @Test(expected=AccessDeniedException.class) public void onlyAbstainVotesDeniesAccessWithDefault() throws Exception { - mgr.setDecisionVoters(Arrays.>asList(abstain, abstain, abstain)); + mgr = new AffirmativeBased(Arrays.>asList(abstain, abstain, abstain)); assertTrue(!mgr.isAllowIfAllAbstainDecisions()); // check default mgr.decide(user, new Object(), attrs); @@ -94,7 +94,7 @@ public class AffirmativeBasedTests { @Test public void testThreeAbstainVotesGrantsAccessIfAllowIfAllAbstainDecisionsIsSet() throws Exception { - mgr.setDecisionVoters(Arrays.>asList(abstain, abstain, abstain)); + mgr = new AffirmativeBased(Arrays.>asList(abstain, abstain, abstain)); mgr.setAllowIfAllAbstainDecisions(true); assertTrue(mgr.isAllowIfAllAbstainDecisions()); // check changed diff --git a/core/src/test/java/org/springframework/security/access/vote/ConsensusBasedTests.java b/core/src/test/java/org/springframework/security/access/vote/ConsensusBasedTests.java index f6bedcc282..d49328da96 100644 --- a/core/src/test/java/org/springframework/security/access/vote/ConsensusBasedTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/ConsensusBasedTests.java @@ -106,7 +106,6 @@ public class ConsensusBasedTests { } private ConsensusBased makeDecisionManager() { - ConsensusBased decisionManager = new ConsensusBased(); RoleVoter roleVoter = new RoleVoter(); DenyVoter denyForSureVoter = new DenyVoter(); DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter(); @@ -114,9 +113,8 @@ public class ConsensusBasedTests { voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); - decisionManager.setDecisionVoters(voters); - return decisionManager; + return new ConsensusBased(voters); } private TestingAuthenticationToken makeTestToken() { diff --git a/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java b/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java index ef626158d8..53359169ec 100644 --- a/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java @@ -39,7 +39,6 @@ public class UnanimousBasedTests extends TestCase { //~ Methods ======================================================================================================== private UnanimousBased makeDecisionManager() { - UnanimousBased decisionManager = new UnanimousBased(); RoleVoter roleVoter = new RoleVoter(); DenyVoter denyForSureVoter = new DenyVoter(); DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter(); @@ -47,13 +46,10 @@ public class UnanimousBasedTests extends TestCase { voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); - decisionManager.setDecisionVoters(voters); - - return decisionManager; + return new UnanimousBased(voters); } private UnanimousBased makeDecisionManagerWithFooBarPrefix() { - UnanimousBased decisionManager = new UnanimousBased(); RoleVoter roleVoter = new RoleVoter(); roleVoter.setRolePrefix("FOOBAR_"); @@ -63,9 +59,7 @@ public class UnanimousBasedTests extends TestCase { voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); - decisionManager.setDecisionVoters(voters); - - return decisionManager; + return new UnanimousBased(voters); } private TestingAuthenticationToken makeTestToken() { diff --git a/core/src/test/java/org/springframework/security/authentication/AuthenticationDetailsSourceImplTests.java b/core/src/test/java/org/springframework/security/authentication/AuthenticationDetailsSourceImplTests.java deleted file mode 100644 index e233be0c8f..0000000000 --- a/core/src/test/java/org/springframework/security/authentication/AuthenticationDetailsSourceImplTests.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.springframework.security.authentication; - -import static org.junit.Assert.*; - -import org.junit.Test; - -/** - * - * @author Luke Taylor - */ -@SuppressWarnings({"deprecation"}) -public class AuthenticationDetailsSourceImplTests { - - @Test - public void buildDetailsReturnsExpectedAuthenticationDetails() { - AuthenticationDetailsSourceImpl ads = new AuthenticationDetailsSourceImpl(); - AuthenticationDetails details = (AuthenticationDetails) ads.buildDetails("the context"); - assertEquals("the context", details.getContext()); - assertEquals(new AuthenticationDetails("the context"), details); - ads.setClazz(AuthenticationDetails.class); - details = (AuthenticationDetails) ads.buildDetails("another context"); - assertEquals("another context", details.getContext()); - } - - @Test(expected=IllegalStateException.class) - public void nonMatchingConstructorIsRejected() { - AuthenticationDetailsSourceImpl ads = new AuthenticationDetailsSourceImpl(); - ads.setClazz(String.class); - ads.buildDetails(new Object()); - } - - @Test(expected=IllegalStateException.class) - public void constructorTakingMultipleArgumentsIsRejected() { - AuthenticationDetailsSourceImpl ads = new AuthenticationDetailsSourceImpl(); - ads.setClazz(TestingAuthenticationToken.class); - ads.buildDetails(null); - } - - @Test - public void authenticationDetailsEqualsBehavesAsExpected() { - AuthenticationDetails details = new AuthenticationDetails("the context"); - assertFalse((new AuthenticationDetails("different context")).equals(details)); - assertFalse((new AuthenticationDetails(null)).equals(details)); - assertFalse(details.equals(new AuthenticationDetails(null))); - assertFalse(details.equals("a string")); - // Just check toString() functions OK - details.toString(); - (new AuthenticationDetails(null)).toString(); - } - -} diff --git a/core/src/test/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisherTests.java b/core/src/test/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisherTests.java index 1a3db9833b..5914841f6c 100644 --- a/core/src/test/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisherTests.java +++ b/core/src/test/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisherTests.java @@ -35,35 +35,29 @@ public class DefaultAuthenticationEventPublisherTests { Exception cause = new Exception(); Object extraInfo = new Object(); publisher.publishAuthenticationFailure(new BadCredentialsException(""), a); - publisher.publishAuthenticationFailure(new BadCredentialsException("", extraInfo), a); publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a); - verify(appPublisher, times(3)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class)); + verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class)); reset(appPublisher); publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a); - publisher.publishAuthenticationFailure(new UsernameNotFoundException("", extraInfo), a); publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a); publisher.publishAuthenticationFailure(new AccountExpiredException(""), a); - publisher.publishAuthenticationFailure(new AccountExpiredException("", extraInfo), a); publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a); publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a); publisher.publishAuthenticationFailure(new DisabledException(""), a); - publisher.publishAuthenticationFailure(new DisabledException("", extraInfo), a); publisher.publishAuthenticationFailure(new DisabledException("", cause), a); publisher.publishAuthenticationFailure(new LockedException(""), a); - publisher.publishAuthenticationFailure(new LockedException("", extraInfo), a); publisher.publishAuthenticationFailure(new LockedException("", cause), a); publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a); publisher.publishAuthenticationFailure(new AuthenticationServiceException("",cause), a); publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a); - publisher.publishAuthenticationFailure(new CredentialsExpiredException("", extraInfo), a); publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a); - verify(appPublisher, times(3)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class)); - verify(appPublisher, times(3)).publishEvent(isA(AuthenticationFailureExpiredEvent.class)); + verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class)); + verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class)); verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class)); - verify(appPublisher, times(3)).publishEvent(isA(AuthenticationFailureDisabledEvent.class)); - verify(appPublisher, times(3)).publishEvent(isA(AuthenticationFailureLockedEvent.class)); + verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class)); + verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class)); verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class)); - verify(appPublisher, times(3)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class)); + verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class)); verifyNoMoreInteractions(appPublisher); } diff --git a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java index 59aeebb9a6..4c97d10e2e 100644 --- a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java @@ -69,10 +69,9 @@ public class ProviderManagerTests { @Test public void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() throws Exception { final Authentication a = mock(Authentication.class); - ProviderManager mgr = new ProviderManager(); + ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichReturns(a))); AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class); mgr.setAuthenticationEventPublisher(publisher); - mgr.setProviders(Arrays.asList(createProviderWhichReturns(a))); Authentication result = mgr.authenticate(a); assertEquals(a, result); @@ -82,37 +81,24 @@ public class ProviderManagerTests { @Test public void authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates() { final Authentication a = mock(Authentication.class); - ProviderManager mgr = new ProviderManager(); + ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a))); AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class); mgr.setAuthenticationEventPublisher(publisher); - mgr.setProviders(Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a))); Authentication result = mgr.authenticate(a); assertSame(a, result); verify(publisher).publishAuthenticationSuccess(result); } - @Test(expected=IllegalArgumentException.class) - public void startupFailsIfProviderListDoesNotContainProviders() throws Exception { - List providers = new ArrayList(); - providers.add("THIS_IS_NOT_A_PROVIDER"); - - ProviderManager mgr = new ProviderManager(); - - mgr.setProviders(providers); - } - @Test(expected=IllegalArgumentException.class) public void testStartupFailsIfProvidersNotSet() throws Exception { - ProviderManager mgr = new ProviderManager(); - mgr.afterPropertiesSet(); + new ProviderManager(null); } @Test public void detailsAreNotSetOnAuthenticationTokenIfAlreadySetByProvider() throws Exception { Object requestDetails = "(Request Details)"; final Object resultDetails = "(Result Details)"; - ProviderManager authMgr = makeProviderManager(); // A provider which sets the details object AuthenticationProvider provider = new AuthenticationProvider() { @@ -126,7 +112,7 @@ public class ProviderManagerTests { } }; - authMgr.setProviders(Arrays.asList(provider)); + ProviderManager authMgr = new ProviderManager(Arrays.asList(provider)); TestingAuthenticationToken request = createAuthenticationToken(); request.setDetails(requestDetails); @@ -150,35 +136,32 @@ public class ProviderManagerTests { @Test public void authenticationExceptionIsIgnoredIfLaterProviderAuthenticates() throws Exception { - ProviderManager mgr = new ProviderManager(); final Authentication authReq = mock(Authentication.class); - mgr.setProviders(Arrays.asList(createProviderWhichThrows(new BadCredentialsException("", new Throwable())), + ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(new BadCredentialsException("", new Throwable())), createProviderWhichReturns(authReq))); assertSame(authReq, mgr.authenticate(mock(Authentication.class))); } @Test public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() throws Exception { - ProviderManager mgr = new ProviderManager(); - mgr.setProviders(Arrays.asList(createProviderWhichThrows(new BadCredentialsException("", "extra")), + ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null))); try { mgr.authenticate(mock(Authentication.class)); fail("Expected BadCredentialsException"); } catch (BadCredentialsException expected) { - assertEquals("extra", expected.getExtraInformation()); } } // SEC-546 @Test public void accountStatusExceptionPreventsCallsToSubsequentProviders() throws Exception { - ProviderManager authMgr = makeProviderManager(); - AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException(""){}); + AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException("") { + }); AuthenticationProvider otherProvider = mock(AuthenticationProvider.class); - authMgr.setProviders(Arrays.asList(iThrowAccountStatusException, otherProvider)); + ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider)); try { authMgr.authenticate(mock(Authentication.class)); @@ -188,22 +171,6 @@ public class ProviderManagerTests { verifyZeroInteractions(otherProvider); } - @Test - public void extraInformationIsClearedIfFlagIsSet() throws Exception { - ProviderManager authMgr = makeProviderManager(); - AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException("", "extra"){}); - - authMgr.setProviders(Arrays.asList(iThrowAccountStatusException)); - authMgr.setClearExtraInformation(true); - - try { - authMgr.authenticate(mock(Authentication.class)); - fail("Expected AccountStatusException"); - } catch (AccountStatusException expected) { - assertNull(expected.getExtraInformation()); - } - } - @Test public void parentAuthenticationIsUsedIfProvidersDontAuthenticate() throws Exception { AuthenticationManager parent = mock(AuthenticationManager.class); @@ -229,15 +196,15 @@ public class ProviderManagerTests { @Test public void providerNotFoundFromParentIsIgnored() throws Exception { - ProviderManager mgr = new ProviderManager(); 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 - mgr.setProviders(Arrays.asList(createProviderWhichThrows(new BadCredentialsException("")))); AuthenticationManager parent = mock(AuthenticationManager.class); when(parent.authenticate(authReq)).thenThrow(new ProviderNotFoundException("")); - mgr.setParent(parent); + + // Set a provider that throws an exception - this is the exception we expect to be propagated + ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(new BadCredentialsException(""))), parent); + mgr.setAuthenticationEventPublisher(publisher); + try { mgr.authenticate(authReq); fail("Expected exception"); @@ -262,7 +229,6 @@ public class ProviderManagerTests { fail("Expected exception"); } catch (BadCredentialsException e) { assertSame(expected, e); - assertSame(authReq, e.getAuthentication()); } verify(publisher).publishAuthenticationFailure(expected, authReq); } @@ -282,7 +248,6 @@ public class ProviderManagerTests { fail("Expected exception"); } catch (LockedException e) { assertSame(expected, e); - assertSame(authReq, e.getAuthentication()); } verify(publisher).publishAuthenticationFailure(expected, authReq); } diff --git a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java index 2bcad8d377..34477ad8a4 100644 --- a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java @@ -37,8 +37,7 @@ public class AnonymousAuthenticationProviderTests { @Test public void testDetectsAnInvalidKey() throws Exception { - AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(); - aap.setKey("qwerty"); + AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); @@ -52,10 +51,8 @@ public class AnonymousAuthenticationProviderTests { @Test public void testDetectsMissingKey() throws Exception { - AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(); - try { - aap.afterPropertiesSet(); + new AnonymousAuthenticationProvider(null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -64,16 +61,13 @@ public class AnonymousAuthenticationProviderTests { @Test public void testGettersSetters() throws Exception { - AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(); - aap.setKey("qwerty"); - aap.afterPropertiesSet(); + AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); assertEquals("qwerty", aap.getKey()); } @Test public void testIgnoresClassesItDoesNotSupport() throws Exception { - AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(); - aap.setKey("qwerty"); + AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A"); assertFalse(aap.supports(TestingAuthenticationToken.class)); @@ -84,8 +78,7 @@ public class AnonymousAuthenticationProviderTests { @Test public void testNormalOperation() throws Exception { - AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(); - aap.setKey("qwerty"); + AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); @@ -97,7 +90,7 @@ public class AnonymousAuthenticationProviderTests { @Test public void testSupports() { - AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(); + AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); assertTrue(aap.supports(AnonymousAuthenticationToken.class)); assertFalse(aap.supports(TestingAuthenticationToken.class)); } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java index 4568517ada..774f0334a8 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java @@ -234,7 +234,7 @@ public class DefaultJaasAuthenticationProviderTests { @Test public void publishNullPublisher() { provider.setApplicationEventPublisher(null); - AuthenticationException ae = new BadCredentialsException("Failed to login", token); + AuthenticationException ae = new BadCredentialsException("Failed to login"); provider.publishFailureEvent(token, ae); provider.publishSuccessEvent(token); diff --git a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java index 75345ac77f..4420f39f7f 100644 --- a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java @@ -34,8 +34,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { //~ Methods ======================================================================================================== public void testDetectsAnInvalidKey() throws Exception { - RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); - aap.setKey("qwerty"); + RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); @@ -48,10 +47,8 @@ public class RememberMeAuthenticationProviderTests extends TestCase { } public void testDetectsMissingKey() throws Exception { - RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); - try { - aap.afterPropertiesSet(); + new RememberMeAuthenticationProvider(null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -59,15 +56,13 @@ public class RememberMeAuthenticationProviderTests extends TestCase { } public void testGettersSetters() throws Exception { - RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); - aap.setKey("qwerty"); + RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); aap.afterPropertiesSet(); assertEquals("qwerty", aap.getKey()); } public void testIgnoresClassesItDoesNotSupport() throws Exception { - RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); - aap.setKey("qwerty"); + RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password","ROLE_A"); assertFalse(aap.supports(TestingAuthenticationToken.class)); @@ -77,8 +72,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { } public void testNormalOperation() throws Exception { - RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); - aap.setKey("qwerty"); + RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("qwerty", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); @@ -89,7 +83,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { } public void testSupports() { - RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); + RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); assertTrue(aap.supports(RememberMeAuthenticationToken.class)); assertFalse(aap.supports(TestingAuthenticationToken.class)); } diff --git a/core/src/test/java/org/springframework/security/core/userdetails/memory/InMemoryDaoTests.java b/core/src/test/java/org/springframework/security/core/userdetails/memory/InMemoryDaoTests.java deleted file mode 100644 index 7c2d1eefe2..0000000000 --- a/core/src/test/java/org/springframework/security/core/userdetails/memory/InMemoryDaoTests.java +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.userdetails.memory; - -import junit.framework.TestCase; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - -import java.util.*; - - -/** - * Tests {@link InMemoryDaoImpl}. - * - * @author Ben Alex - */ -@SuppressWarnings({"deprecation"}) -public class InMemoryDaoTests extends TestCase { - - //~ Methods ======================================================================================================== - - private UserMap makeUserMap() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText("rod=koala,ROLE_ONE,ROLE_TWO,enabled\nScott=wombat,ROLE_ONE,ROLE_TWO,enabled"); - - return (UserMap) editor.getValue(); - } - - public void testLookupFails() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - dao.setUserMap(makeUserMap()); - dao.afterPropertiesSet(); - - try { - dao.loadUserByUsername("UNKNOWN_USER"); - fail("Should have thrown UsernameNotFoundException"); - } catch (UsernameNotFoundException expected) { - assertTrue(true); - } - } - - public void testLookupSuccess() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - dao.setUserMap(makeUserMap()); - dao.afterPropertiesSet(); - assertEquals("koala", dao.loadUserByUsername("rod").getPassword()); - assertEquals("wombat", dao.loadUserByUsername("scott").getPassword()); - } - - public void testLookupSuccessWithMixedCase() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - dao.setUserMap(makeUserMap()); - dao.afterPropertiesSet(); - assertEquals("koala", dao.loadUserByUsername("rod").getPassword()); - assertEquals("wombat", dao.loadUserByUsername("ScOTt").getPassword()); - } - - public void testStartupFailsIfUserMapNotSet() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - - try { - dao.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } - } - - public void testStartupFailsIfUserMapSetToNull() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - dao.setUserMap(null); - - try { - dao.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } - } - - public void testStartupSuccessIfUserMapSet() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - dao.setUserMap(makeUserMap()); - dao.afterPropertiesSet(); - assertEquals(2, dao.getUserMap().getUserCount()); - } - - public void testUseOfExternalPropertiesObject() throws Exception { - InMemoryDaoImpl dao = new InMemoryDaoImpl(); - Properties props = new Properties(); - props.put("rod", "koala,ROLE_ONE,ROLE_TWO,enabled"); - props.put("scott", "wombat,ROLE_ONE,ROLE_TWO,enabled"); - dao.setUserProperties(props); - assertEquals("koala", dao.loadUserByUsername("rod").getPassword()); - assertEquals("wombat", dao.loadUserByUsername("scott").getPassword()); - } -} diff --git a/core/src/test/java/org/springframework/security/core/userdetails/memory/UserMapEditorTests.java b/core/src/test/java/org/springframework/security/core/userdetails/memory/UserMapEditorTests.java deleted file mode 100644 index 60d871a59c..0000000000 --- a/core/src/test/java/org/springframework/security/core/userdetails/memory/UserMapEditorTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.userdetails.memory; - -import junit.framework.TestCase; -import org.springframework.security.core.authority.AuthorityUtils; - - -/** - * Tests {@link UserMapEditor}. - * - * @author Ben Alex - */ -@SuppressWarnings("deprecation") -public class UserMapEditorTests extends TestCase { - - //~ Methods ======================================================================================================== - - public void testConvertedIntoUserSuccessfullyWhenDisabled() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText("rod=koala,ROLE_ONE,ROLE_TWO,disabled"); - - UserMap map = (UserMap) editor.getValue(); - assertTrue(!map.getUser("rod").isEnabled()); - } - - public void testConvertedIntoUserSuccessfullyWhenEnabled() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText("rod=koala,ROLE_ONE,ROLE_TWO"); - - UserMap map = (UserMap) editor.getValue(); - assertEquals("rod", map.getUser("rod").getUsername()); - assertEquals("koala", map.getUser("rod").getPassword()); - assertTrue(AuthorityUtils.authorityListToSet(map.getUser("rod").getAuthorities()).contains("ROLE_ONE")); - assertTrue(AuthorityUtils.authorityListToSet(map.getUser("rod").getAuthorities()).contains("ROLE_TWO")); - assertTrue(map.getUser("rod").isEnabled()); - } - - public void testEmptyStringReturnsEmptyMap() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText(""); - - UserMap map = (UserMap) editor.getValue(); - assertEquals(0, map.getUserCount()); - } - - public void testMalformedStringReturnsEmptyMap() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText("MALFORMED_STRING"); - - UserMap map = (UserMap) editor.getValue(); - assertEquals(0, map.getUserCount()); - } - - public void testMultiUserParsing() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText("rod=koala,ROLE_ONE,ROLE_TWO,enabled\r\nscott=wombat,ROLE_ONE,ROLE_TWO,enabled"); - - UserMap map = (UserMap) editor.getValue(); - assertEquals("rod", map.getUser("rod").getUsername()); - assertEquals("scott", map.getUser("scott").getUsername()); - } - - public void testNullReturnsEmptyMap() { - UserMapEditor editor = new UserMapEditor(); - editor.setAsText(null); - - UserMap map = (UserMap) editor.getValue(); - assertEquals(0, map.getUserCount()); - } -} diff --git a/core/src/test/java/org/springframework/security/core/userdetails/memory/UserMapTests.java b/core/src/test/java/org/springframework/security/core/userdetails/memory/UserMapTests.java deleted file mode 100644 index 17bcb7b96d..0000000000 --- a/core/src/test/java/org/springframework/security/core/userdetails/memory/UserMapTests.java +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.core.userdetails.memory; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - - -/** - * Tests {@link UserMap}. - * - * @author Ben Alex - */ -@SuppressWarnings("deprecation") -public class UserMapTests { - @Test - public void testAddAndRetrieveUser() { - UserDetails rod = new User("rod", "koala", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO")); - UserDetails scott = new User("scott", "wombat", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_THREE")); - UserDetails peter = new User("peter", "opal", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_FOUR")); - UserMap map = new UserMap(); - map.addUser(rod); - map.addUser(scott); - map.addUser(peter); - assertEquals(3, map.getUserCount()); - - assertEquals(rod, map.getUser("rod")); - assertEquals(scott, map.getUser("scott")); - assertEquals(peter, map.getUser("peter")); - } - - @Test - public void nullUserCannotBeAdded() { - UserMap map = new UserMap(); - assertEquals(0, map.getUserCount()); - - try { - map.addUser(null); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } - } - - @Test - public void unknownUserIsNotRetrieved() { - UserDetails rod = new User("rod", "koala", true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO")); - UserMap map = new UserMap(); - assertEquals(0, map.getUserCount()); - map.addUser(rod); - assertEquals(1, map.getUserCount()); - - try { - map.getUser("scott"); - fail("Should have thrown UsernameNotFoundException"); - } catch (UsernameNotFoundException expected) { - assertTrue(true); - } - } -} diff --git a/docs/manual/src/asciidoc/index.adoc b/docs/manual/src/asciidoc/index.adoc index 621689b42a..c8fd620872 100644 --- a/docs/manual/src/asciidoc/index.adoc +++ b/docs/manual/src/asciidoc/index.adoc @@ -2441,7 +2441,7 @@ The `FilterSecurityInterceptor` can be configured with configuration attributes It should be noted that the `FilterSecurityInterceptor.setSecurityMetadataSource()` method actually expects an instance of `FilterInvocationSecurityMetadataSource`. This is a marker interface which subclasses`SecurityMetadataSource`. It simply denotes the `SecurityMetadataSource` understands `FilterInvocation` s. In the interests of simplicity we'll continue to refer to the `FilterInvocationSecurityMetadataSource` as a `SecurityMetadataSource`, as the distinction is of little relevance to most users. -The `SecurityMetadataSource` created by the namespace syntax obtains the configuration attributes for a particular `FilterInvocation` by matching the request URL against the configured `pattern` attributes. This behaves in the same way as it does for namespace configuration. The default is to treat all expressions as Apache Ant paths and regular expressions are also supported for more complex cases. The `path-type` attribute is used to specify the type of pattern being used. It is not possible to mix expression syntaxes within the same definition. As an example, the previous configuration using regular expressions instead of Ant paths would be written as follows: +The `SecurityMetadataSource` created by the namespace syntax obtains the configuration attributes for a particular `FilterInvocation` by matching the request URL against the configured `pattern` attributes. This behaves in the same way as it does for namespace configuration. The default is to treat all expressions as Apache Ant paths and regular expressions are also supported for more complex cases. The `request-matcher` attribute is used to specify the type of pattern being used. It is not possible to mix expression syntaxes within the same definition. As an example, the previous configuration using regular expressions instead of Ant paths would be written as follows: [source,xml] ---- @@ -2451,7 +2451,7 @@ The `SecurityMetadataSource` created by the namespace syntax obtains the configu - + @@ -6488,11 +6488,6 @@ The attributes on the `` element control some of the properties on the cor Optional attribute specifying the ID of the `AccessDecisionManager` implementation which should be used for authorizing HTTP requests. By default an `AffirmativeBased` implementation is used for with a `RoleVoter` and an `AuthenticatedVoter`. -[[nsa-http-access-denied-page]] -* **access-denied-page** -Deprecated in favour of the <> child element. - - [[nsa-http-authentication-manager-ref]] * **authentication-manager-ref** A reference to the `AuthenticationManager` used for the `FilterChain` created by this http element. @@ -6537,11 +6532,6 @@ A bean identifier, used for referring to the bean elsewhere in the context. Corresponds to the `observeOncePerRequest` property of `FilterSecurityInterceptor`. Defaults to `true`. -[[nsa-http-path-type]] -* **path-type** -Deprecated in favor of <>. - - [[nsa-http-pattern]] * **pattern** Defining a pattern for the <> element controls the requests which will be filtered through the list of filters which it defines. The interpretation is dependent on the configured <>. If no pattern is defined, all requests will be matched, so the most specific patterns should be declared first. @@ -7080,7 +7070,6 @@ This element is used to define the set of URL patterns that the application is i ===== Parent Elements of -* <> * <> * <> @@ -7603,14 +7592,9 @@ Used to explicitly configure a FilterChainProxy instance with a FilterChainMap ===== Attributes -[[nsa-filter-chain-map-path-type]] -* **path-type** -Superseded by the <> attribute - - [[nsa-filter-chain-map-request-matcher]] * **request-matcher** -Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. +Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. [[nsa-filter-chain-map-children]] @@ -7653,48 +7637,6 @@ A-pattern that creates RequestMatcher in combination with the < -Deprecated synonym for filter-security-metadata-source - - -[[nsa-filter-invocation-definition-source-attributes]] -===== Attributes - - -[[nsa-filter-invocation-definition-source-id]] -* **id** -A bean identifier, used for referring to the bean elsewhere in the context. - - -[[nsa-filter-invocation-definition-source-lowercase-comparisons]] -* **lowercase-comparisons** -Compare after forcing to lowercase - - -[[nsa-filter-invocation-definition-source-path-type]] -* **path-type** -Superseded by <> - - -[[nsa-filter-invocation-definition-source-request-matcher]] -* **request-matcher** -Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. - - -[[nsa-filter-invocation-definition-source-use-expressions]] -* **use-expressions** -Enables the use of expressions in the 'access' attributes in elements rather than the traditional list of configuration attributes. Defaults to 'false'. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to 'true', access will be granted. - - -[[nsa-filter-invocation-definition-source-children]] -===== Child Elements of - - -* <> - - - [[nsa-filter-security-metadata-source]] ==== Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error. @@ -7714,14 +7656,9 @@ A bean identifier, used for referring to the bean elsewhere in the context. Compare after forcing to lower case -[[nsa-filter-security-metadata-source-path-type]] -* **path-type** -Superseded by <> - - [[nsa-filter-security-metadata-source-request-matcher]] * **request-matcher** -Supersedes the 'path-type' attribute. Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. +Defines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions. [[nsa-filter-security-metadata-source-use-expressions]] diff --git a/itest/context/src/integration-test/resources/filter-chain-performance-app-context.xml b/itest/context/src/integration-test/resources/filter-chain-performance-app-context.xml index d162c6d229..2044156cfa 100644 --- a/itest/context/src/integration-test/resources/filter-chain-performance-app-context.xml +++ b/itest/context/src/integration-test/resources/filter-chain-performance-app-context.xml @@ -11,25 +11,25 @@ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> - + - + - + - + @@ -43,8 +43,7 @@ - - + @@ -67,7 +66,7 @@ - + @@ -79,12 +78,12 @@ - - + - + - + + diff --git a/itest/context/src/integration-test/resources/http-extra-fsi-app-context.xml b/itest/context/src/integration-test/resources/http-extra-fsi-app-context.xml index e1a8aa833a..290616edf7 100644 --- a/itest/context/src/integration-test/resources/http-extra-fsi-app-context.xml +++ b/itest/context/src/integration-test/resources/http-extra-fsi-app-context.xml @@ -31,12 +31,12 @@ - - + - + + diff --git a/itest/context/src/integration-test/resources/sec-936-app-context.xml b/itest/context/src/integration-test/resources/sec-936-app-context.xml index 3ab778af80..dc3a11f9dd 100755 --- a/itest/context/src/integration-test/resources/sec-936-app-context.xml +++ b/itest/context/src/integration-test/resources/sec-936-app-context.xml @@ -16,13 +16,13 @@ - - + - + + diff --git a/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml b/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml index af2d81a67e..43e270e8db 100644 --- a/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml +++ b/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml @@ -21,7 +21,7 @@ - + @@ -30,8 +30,8 @@ - - + + diff --git a/itest/web/src/main/webapp/WEB-INF/security.tld b/itest/web/src/main/webapp/WEB-INF/security.tld index ce94181785..01961e8968 100644 --- a/itest/web/src/main/webapp/WEB-INF/security.tld +++ b/itest/web/src/main/webapp/WEB-INF/security.tld @@ -60,35 +60,6 @@ false - - - A comma separated list of roles which the user must not have - for the body to be output. Deprecated in favour of the access expression. - - ifNotGranted - false - true - - - - - A comma separated list of roles which the user must all - possess for the body to be output. Deprecated in favour of the access expression. - - ifAllGranted - false - true - - - - - A comma separated list of roles, one of which the user must - possess for the body to be output. Deprecated in favour of the access expression. - - ifAnyGranted - false - true - diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java index 77cd7b62be..f661700e81 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticator.java @@ -89,7 +89,7 @@ public final class PasswordComparisonAuthenticator extends AbstractLdapAuthentic } if (user == null) { - throw new UsernameNotFoundException("User not found: " + username, username); + throw new UsernameNotFoundException("User not found: " + username); } if (logger.isDebugEnabled()) { diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java index 43bb830527..a40ac2847d 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java @@ -286,7 +286,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda new Object[]{bindPrincipal}); } catch (IncorrectResultSizeDataAccessException incorrectResults) { if (incorrectResults.getActualSize() == 0) { - UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException("User " + username + " not found in directory.", username); + UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException("User " + username + " not found in directory."); userNameNotFoundException.initCause(incorrectResults); throw badCredentials(userNameNotFoundException); } diff --git a/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java b/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java index 8ea6f89d4b..164d167a95 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java +++ b/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java @@ -117,7 +117,7 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch { } catch (IncorrectResultSizeDataAccessException notFound) { if (notFound.getActualSize() == 0) { - throw new UsernameNotFoundException("User " + username + " not found in directory.", username); + throw new UsernameNotFoundException("User " + username + " not found in directory."); } // Search should never return multiple results if properly configured, so just rethrow throw notFound; diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java index 252a30b6a4..bbf1dc559a 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/DefaultLdapAuthoritiesPopulator.java @@ -85,9 +85,6 @@ import java.util.Set; * A search for roles for user "uid=ben,ou=people,dc=springframework,dc=org" would return the single granted authority * "ROLE_DEVELOPER". *

- * Note that case-conversion, use of the role prefix and setting a default role are better performed using a - * {@code GrantedAuthoritiesMapper} and are now deprecated. - *

* The single-level search is performed by default. Setting the searchSubTree property to true will enable * a search of the entire subtree under groupSearchBase. * @@ -250,9 +247,8 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator } /** - * @deprecated Convert case in the {@code AuthenticationProvider} using a {@code GrantedAuthoritiesMapper}. + * Convert the role to uppercase */ - @Deprecated public void setConvertToUpperCase(boolean convertToUpperCase) { this.convertToUpperCase = convertToUpperCase; } @@ -261,9 +257,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator * The default role which will be assigned to all users. * * @param defaultRole the role name, including any desired prefix. - * @deprecated Assign a default role in the {@code AuthenticationProvider} using a {@code GrantedAuthoritiesMapper}. */ - @Deprecated public void setDefaultRole(String defaultRole) { Assert.notNull(defaultRole, "The defaultRole property cannot be set to null"); this.defaultRole = new SimpleGrantedAuthority(defaultRole); @@ -282,10 +276,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator /** * Sets the prefix which will be prepended to the values loaded from the directory. * Defaults to "ROLE_" for compatibility with RoleVoter/tt>. - * - * @deprecated Map the authorities in the {@code AuthenticationProvider} using a {@code GrantedAuthoritiesMapper}. */ - @Deprecated public void setRolePrefix(String rolePrefix) { Assert.notNull(rolePrefix, "rolePrefix must not be null"); this.rolePrefix = rolePrefix; @@ -312,7 +303,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator /** * Returns the current LDAP template. - * Method available so that classes extending this can override the template used + * Method available so that classes extending this can override the template used * @return the LDAP template * @see {@link org.springframework.security.ldap.SpringSecurityLdapTemplate} */ diff --git a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java index 1700927726..8beaef52ca 100644 --- a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java +++ b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java @@ -62,27 +62,6 @@ public class OpenID4JavaConsumer implements OpenIDConsumer { this(new ConsumerManager(), new NullAxFetchListFactory()); } - /** - * @deprecated use the {@link AxFetchListFactory} version instead. - */ - @Deprecated - public OpenID4JavaConsumer(List attributes) throws ConsumerException { - this(new ConsumerManager(), attributes); - } - - @Deprecated - public OpenID4JavaConsumer(ConsumerManager consumerManager, final List attributes) - throws ConsumerException { - this.consumerManager = consumerManager; - this.attributesToFetchFactory = new AxFetchListFactory() { - private final List fetchAttrs = Collections.unmodifiableList(attributes); - - public List createAttributeList(String identifier) { - return fetchAttrs; - } - }; - } - public OpenID4JavaConsumer(AxFetchListFactory attributesToFetchFactory) throws ConsumerException { this(new ConsumerManager(), attributesToFetchFactory); } diff --git a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java index 32f7fd778b..dbc0b5d034 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java @@ -39,7 +39,7 @@ public class OpenID4JavaConsumerTests { when(mgr.authenticate(any(DiscoveryInformation.class), anyString(), anyString())).thenReturn(authReq); when(mgr.associate(anyList())).thenReturn(di); - OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, attributes); + OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new MockAttributesFactory()); MockHttpServletRequest request = new MockHttpServletRequest(); consumer.beginConsumption(request, "", "", ""); @@ -195,11 +195,16 @@ public class OpenID4JavaConsumerTests { consumer.endConsumption(new MockHttpServletRequest()); } - @SuppressWarnings("deprecation") @Test public void additionalConstructorsWork() throws Exception { new OpenID4JavaConsumer(); - new OpenID4JavaConsumer(attributes); + new OpenID4JavaConsumer(new MockAttributesFactory()); } + private class MockAttributesFactory implements AxFetchListFactory { + + public List createAttributeList(String identifier) { + return attributes; + } + } } diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java index 711fa047d0..8d189eeef6 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java @@ -45,7 +45,9 @@ public class OpenIDAuthenticationFilterTests { @Test public void testFilterOperation() throws Exception { - MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_PATH); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setServletPath(REQUEST_PATH); + req.setRequestURI(REQUEST_PATH); req.setServerPort(8080); MockHttpServletResponse response = new MockHttpServletResponse(); diff --git a/samples/cas/sample-xml/src/main/webapp/WEB-INF/applicationContext-security.xml b/samples/cas/sample-xml/src/main/webapp/WEB-INF/applicationContext-security.xml index 923d86a09b..55f8e20f54 100644 --- a/samples/cas/sample-xml/src/main/webapp/WEB-INF/applicationContext-security.xml +++ b/samples/cas/sample-xml/src/main/webapp/WEB-INF/applicationContext-security.xml @@ -62,7 +62,9 @@ p:proxyGrantingTicketStorage-ref="pgtStorage" p:proxyReceptorUrl="/j_spring_cas_security_proxyreceptor"> - + + + Login to CAS failed! - Your CAS credentials were rejected.

- Reason: -<% - Exception error = ((AuthenticationException) session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)); - if(error != null) { -%> -<%= error.getMessage() %> -<% -} -%> + Your CAS credentials were rejected.
diff --git a/samples/contacts-xml/src/main/resources/applicationContext-common-authorization.xml b/samples/contacts-xml/src/main/resources/applicationContext-common-authorization.xml index 355e611c6b..547aea2a82 100644 --- a/samples/contacts-xml/src/main/resources/applicationContext-common-authorization.xml +++ b/samples/contacts-xml/src/main/resources/applicationContext-common-authorization.xml @@ -22,6 +22,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/samples/contacts-xml/src/main/webapp/switchUser.jsp b/samples/contacts-xml/src/main/webapp/switchUser.jsp index f052fe262c..ab8615a326 100644 --- a/samples/contacts-xml/src/main/webapp/switchUser.jsp +++ b/samples/contacts-xml/src/main/webapp/switchUser.jsp @@ -25,8 +25,7 @@

- Your 'su' attempt was not successful, try again.

- Reason: <%= ((AuthenticationException) session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)).getMessage() %> + Your 'su' attempt was not successful, try again.

diff --git a/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml b/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml index a84a65e914..59853dbcc8 100755 --- a/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml +++ b/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml @@ -128,14 +128,14 @@ - - + - + + @@ -147,6 +147,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java b/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java index 833665b59c..cf6c549685 100755 --- a/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java +++ b/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java @@ -14,9 +14,6 @@ import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(locations={"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-secure.xml"}) public class SecureDmsIntegrationTests extends DmsIntegrationTests { -// @Autowired -// private AclService aclService; - @Test public void testBasePopulation() { assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY")); @@ -26,18 +23,6 @@ public class SecureDmsIntegrationTests extends DmsIntegrationTests { assertEquals(100, jdbcTemplate.queryForInt("select count(id) from ACL_OBJECT_IDENTITY")); assertEquals(115, jdbcTemplate.queryForInt("select count(id) from ACL_ENTRY")); } - /* - public void testItOut() { - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("rod", "password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SUPERVISOR")})); - - - AbstractElement[] elements = documentDao.findElements(Directory.ROOT_DIRECTORY); - ObjectIdentity oid = new ObjectIdentityImpl(elements[0]); - //ObjectIdentity oid = new ObjectIdentityImpl(Directory.class, new Long(3)); - Acl acl = aclService.readAclById(oid); - System.out.println(acl); - - }*/ public void testMarissaRetrieval() { process("rod", "koala", true); diff --git a/samples/preauth-xml/src/main/webapp/WEB-INF/applicationContext-security.xml b/samples/preauth-xml/src/main/webapp/WEB-INF/applicationContext-security.xml index 8886144ce6..5f62ef19ba 100644 --- a/samples/preauth-xml/src/main/webapp/WEB-INF/applicationContext-security.xml +++ b/samples/preauth-xml/src/main/webapp/WEB-INF/applicationContext-security.xml @@ -12,7 +12,7 @@ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> - + @@ -58,30 +58,28 @@ - - - + - - + - + + - + - + diff --git a/sandbox/heavyduty/src/main/webapp/login.jsp b/sandbox/heavyduty/src/main/webapp/login.jsp index fbe58d7204..382a13276c 100755 --- a/sandbox/heavyduty/src/main/webapp/login.jsp +++ b/sandbox/heavyduty/src/main/webapp/login.jsp @@ -11,16 +11,6 @@

CUSTOM SPRING SECURITY LOGIN

- <%-- this form-login-page form is also used as the - form-error-page to ask for a login again. - --%> - <% if (session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY) != null) { %> - - Your login attempt was not successful, try again.

- Reason: <%= ((AuthenticationException) session.getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)).getMessage() %> -
- <% } %> -
diff --git a/sandbox/heavyduty/src/main/webapp/secure/extreme/index.jsp b/sandbox/heavyduty/src/main/webapp/secure/extreme/index.jsp index f4e377dc50..60077d1d6e 100755 --- a/sandbox/heavyduty/src/main/webapp/secure/extreme/index.jsp +++ b/sandbox/heavyduty/src/main/webapp/secure/extreme/index.jsp @@ -5,7 +5,7 @@

VERY Secure Page

This is a protected page. You can only see me if you are a supervisor. - + You have "ROLE_SUPERVISOR" (this text is surrounded by <authz:authorize> tags). diff --git a/sandbox/heavyduty/src/main/webapp/secure/index.jsp b/sandbox/heavyduty/src/main/webapp/secure/index.jsp index ef87083a45..1ebf67e6a3 100755 --- a/sandbox/heavyduty/src/main/webapp/secure/index.jsp +++ b/sandbox/heavyduty/src/main/webapp/secure/index.jsp @@ -8,8 +8,8 @@ This is a protected page. You can get to me if you've been remembered, or if you've authenticated this session.

- - You are a supervisor! You can therefore see the extremely secure page.

+ + You are a supervisor! You can therefore see the extremely secure page.

Properties obtained using <sec:authentication /> tag

diff --git a/sandbox/webflow/src/main/webapp/secure/extreme/index.jsp b/sandbox/webflow/src/main/webapp/secure/extreme/index.jsp index f4e377dc50..60077d1d6e 100644 --- a/sandbox/webflow/src/main/webapp/secure/extreme/index.jsp +++ b/sandbox/webflow/src/main/webapp/secure/extreme/index.jsp @@ -5,7 +5,7 @@

VERY Secure Page

This is a protected page. You can only see me if you are a supervisor. - + You have "ROLE_SUPERVISOR" (this text is surrounded by <authz:authorize> tags). diff --git a/sandbox/webflow/src/main/webapp/secure/index.jsp b/sandbox/webflow/src/main/webapp/secure/index.jsp index 873e2553b1..fe65dd5bbe 100644 --- a/sandbox/webflow/src/main/webapp/secure/index.jsp +++ b/sandbox/webflow/src/main/webapp/secure/index.jsp @@ -8,8 +8,8 @@ This is a protected page. You can get to me if you've been remembered, or if you've authenticated this session.

- - You are a supervisor! You can therefore see the extremely secure page.

+ + You are a supervisor! You can therefore see the extremely secure page.

Properties obtained using <sec:authentication /> tag

diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java index 6ac7d6546c..d2376b698b 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java @@ -16,11 +16,7 @@ package org.springframework.security.taglibs.authz; import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.Map; -import java.util.Set; import javax.servlet.FilterChain; import javax.servlet.ServletContext; @@ -37,7 +33,6 @@ import org.springframework.expression.ParseException; import org.springframework.security.access.expression.ExpressionUtils; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.WebAttributes; @@ -63,10 +58,6 @@ public abstract class AbstractAuthorizeTag { private String access; private String url; private String method = "GET"; - private String ifAllGranted; - private String ifAnyGranted; - private String ifNotGranted; - /** * This method allows subclasses to provide a way to access the ServletRequest according to the rendering * technology. @@ -91,7 +82,6 @@ public abstract class AbstractAuthorizeTag { *
    *
  • access
  • *
  • url, method
  • - *
  • ifAllGranted, ifAnyGranted, ifNotGranted
  • *
* The above combinations are mutually exclusive and evaluated in the given order. * @@ -108,55 +98,13 @@ public abstract class AbstractAuthorizeTag { isAuthorized = authorizeUsingUrlCheck(); } else { - isAuthorized = authorizeUsingGrantedAuthorities(); + isAuthorized = false; } return isAuthorized; } - /** - * Make an authorization decision by considering ifAllGranted, ifAnyGranted, and ifNotGranted. All 3 or any - * combination can be provided. All provided attributes must evaluate to true. - * - * @return the result of the authorization decision - */ - public boolean authorizeUsingGrantedAuthorities() { - boolean hasTextAllGranted = StringUtils.hasText(getIfAllGranted()); - boolean hasTextAnyGranted = StringUtils.hasText(getIfAnyGranted()); - boolean hasTextNotGranted = StringUtils.hasText(getIfNotGranted()); - - if ((!hasTextAllGranted) && (!hasTextAnyGranted) && (!hasTextNotGranted)) { - return false; - } - - final Collection granted = getPrincipalAuthorities(); - final Set grantedRoles = authoritiesToRoles(granted); - - if (hasTextAllGranted) { - final Set requiredRoles = splitRoles(getIfAllGranted()); - if (!grantedRoles.containsAll(requiredRoles)) { - return false; - } - } - - if (hasTextAnyGranted) { - final Set expectOneOfRoles = splitRoles(getIfAnyGranted()); - if (!containsAnyValue(grantedRoles, expectOneOfRoles)) { - return false; - } - } - - if (hasTextNotGranted) { - final Set expectNoneOfRoles = splitRoles(getIfNotGranted()); - if (containsAnyValue(expectNoneOfRoles, grantedRoles)) { - return false; - } - } - - return true; - } - /** * Make an authorization decision based on a Spring EL expression. See the "Expression-Based Access Control" chapter * in Spring Security for details on what expressions can be used. @@ -234,82 +182,8 @@ public abstract class AbstractAuthorizeTag { this.method = (method != null) ? method.toUpperCase() : null; } - public String getIfAllGranted() { - return ifAllGranted; - } - - public void setIfAllGranted(String ifAllGranted) { - this.ifAllGranted = ifAllGranted; - } - - public String getIfAnyGranted() { - return ifAnyGranted; - } - - public void setIfAnyGranted(String ifAnyGranted) { - this.ifAnyGranted = ifAnyGranted; - } - - public String getIfNotGranted() { - return ifNotGranted; - } - - public void setIfNotGranted(String ifNotGranted) { - this.ifNotGranted = ifNotGranted; - } - /*------------- Private helper methods -----------------*/ - private Collection getPrincipalAuthorities() { - Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); - if (null == currentUser) { - return Collections.emptyList(); - } - return currentUser.getAuthorities(); - } - - /** - * Splits the authorityString using "," as a delimiter into a Set. - * @param authorityString - * @return - */ - private Set splitRoles(String authorityString) { - String[] rolesArray = StringUtils.tokenizeToStringArray(authorityString, ","); - Set roles = new HashSet(rolesArray.length); - for(String role : rolesArray) { - roles.add(role); - } - return roles; - } - - /** - * Returns true if any of the values are contained in toTest. Otherwise, false. - * @param toTest Check this Set to see if any of the values are contained in it. - * @param values The values to check if they are in toTest. - * @return - */ - private boolean containsAnyValue(Set toTest, Collection values) { - for(String value : values) { - if(toTest.contains(value)) { - return true; - } - } - return false; - } - - private Set authoritiesToRoles(Collection c) { - Set target = new HashSet(); - for (GrantedAuthority authority : c) { - if (null == authority.getAuthority()) { - throw new IllegalArgumentException( - "Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process " - + authority.toString()); - } - target.add(authority.getAuthority()); - } - return target; - } - @SuppressWarnings({ "unchecked", "rawtypes" }) private SecurityExpressionHandler getExpressionHandler() throws IOException { ApplicationContext appContext = WebApplicationContextUtils diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/velocity/Authz.java b/taglibs/src/main/java/org/springframework/security/taglibs/velocity/Authz.java deleted file mode 100644 index d8d7f4902d..0000000000 --- a/taglibs/src/main/java/org/springframework/security/taglibs/velocity/Authz.java +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.velocity; - - -import org.springframework.context.ApplicationContext; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.userdetails.UserDetails; - - -/** - * @author Wang Qi - */ -public interface Authz { - //~ Methods ======================================================================================================== - - /** - * all the listed roles must be granted to return true, otherwise false; - * - * @param roles - comma separate GrantedAuthoritys - * - * @return granted (true|false) - */ - boolean allGranted(String roles); - - /** - * any the listed roles must be granted to return true, otherwise false; - * - * @param roles - comma separate GrantedAuthoritys - * - * @return granted (true|false) - */ - boolean anyGranted(String roles); - - /** - * get Spring application context which contains - * - */ - ApplicationContext getAppCtx(); - - /** - * return the principal's name, supports the various type of principals that can exist in the {@link - * Authentication} object, such as a String or {@link UserDetails} instance - * - * @return string representation of principal's name - */ - String getPrincipal(); - - /** - * none the listed roles must be granted to return true, otherwise false; - * - * @param roles - comma separate GrantedAuthoritys - * - * @return granted (true|false) - */ - boolean noneGranted(String roles); - - /** - * set Spring application context which contains Acegi related bean - * - */ - void setAppCtx(ApplicationContext appCtx); -} diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/velocity/AuthzImpl.java b/taglibs/src/main/java/org/springframework/security/taglibs/velocity/AuthzImpl.java deleted file mode 100644 index 56fa3b1847..0000000000 --- a/taglibs/src/main/java/org/springframework/security/taglibs/velocity/AuthzImpl.java +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.velocity; - -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.Tag; - -import org.springframework.context.ApplicationContext; -import org.springframework.security.taglibs.authz.AuthenticationTag; -import org.springframework.security.taglibs.authz.JspAuthorizeTag; - - -/** - * I decided to wrap several JSP tag in one class, so I have to using inner class to wrap these JSP tag. To using - * this class, you need to inject Spring Context via SetAppCtx() method. AclTag need Spring Context to get AclManger - * bean. - */ -public class AuthzImpl implements Authz { - //~ Static fields/initializers ===================================================================================== - - static final int ALL_GRANTED = 1; - static final int ANY_GRANTED = 2; - static final int NONE_GRANTED = 3; - - //~ Instance fields ================================================================================================ - - private ApplicationContext appCtx; - - //~ Methods ======================================================================================================== - - public boolean allGranted(String roles) { - return ifGranted(roles, ALL_GRANTED); - } - - public boolean anyGranted(String roles) { - return ifGranted(roles, ANY_GRANTED); - } - - public ApplicationContext getAppCtx() { - return appCtx; - } - - /** - * implementation of AuthenticationTag - */ - public String getPrincipal() { - MyAuthenticationTag authenticationTag = new MyAuthenticationTag(); - - authenticationTag.setProperty("name"); - - try { - authenticationTag.doEndTag(); - } catch (JspException je) { - je.printStackTrace(); - throw new IllegalArgumentException(je.getMessage()); - } - - return authenticationTag.getLastMessage(); - } - - /** - * implementation of JspAuthorizeTag - */ - private boolean ifGranted(String roles, int grantType) { - JspAuthorizeTag authorizeTag = new JspAuthorizeTag(); - - int result; - - try { - switch (grantType) { - case ALL_GRANTED: - authorizeTag.setIfAllGranted(roles); - - break; - - case ANY_GRANTED: - authorizeTag.setIfAnyGranted(roles); - - break; - - case NONE_GRANTED: - authorizeTag.setIfNotGranted(roles); - - break; - - default: - throw new IllegalArgumentException("invalid granted type : " + grantType + " role=" + roles); - } - - result = authorizeTag.doStartTag(); - } catch (JspException je) { - throw new IllegalArgumentException(je.getMessage()); - } - - return Tag.EVAL_BODY_INCLUDE == result; - } - - public boolean noneGranted(String roles) { - return ifGranted(roles, NONE_GRANTED); - } - - /** - * test case can use this class to mock application context with aclManager bean in it. - */ - public void setAppCtx(ApplicationContext appCtx) { - this.appCtx = appCtx; - } - - //~ Inner Classes ================================================================================================== - - /** - * it must output somthing to JSP page, so have to override the writeMessage method to avoid JSP related - * operation. Get Idea from Acegi Test class. - */ - private class MyAuthenticationTag extends AuthenticationTag { - private static final long serialVersionUID = -1094246833893599161L; - String lastMessage = null; - - public String getLastMessage() { - return lastMessage; - } - - protected void writeMessage(String msg) throws JspException { - lastMessage = msg; - } - } -} diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/velocity/package-info.java b/taglibs/src/main/java/org/springframework/security/taglibs/velocity/package-info.java deleted file mode 100644 index 0783ebc077..0000000000 --- a/taglibs/src/main/java/org/springframework/security/taglibs/velocity/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -package org.springframework.security.taglibs.velocity; - diff --git a/taglibs/src/main/resources/META-INF/security.tld b/taglibs/src/main/resources/META-INF/security.tld index 830ed7b8cf..f8ecf59892 100644 --- a/taglibs/src/main/resources/META-INF/security.tld +++ b/taglibs/src/main/resources/META-INF/security.tld @@ -74,36 +74,6 @@ false false - - - - A comma separated list of roles which the user must not have - for the body to be output. Deprecated in favour of the access expression. - - ifNotGranted - false - true - - - - - A comma separated list of roles which the user must all - possess for the body to be output. Deprecated in favour of the access expression. - - ifAllGranted - false - true - - - - - A comma separated list of roles, one of which the user must - possess for the body to be output. Deprecated in favour of the access expression. - - ifAnyGranted - false - true - diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagAttributeTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagAttributeTests.java deleted file mode 100644 index 19fc4b02df..0000000000 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagAttributeTests.java +++ /dev/null @@ -1,91 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.authz; - - -import static org.junit.Assert.assertEquals; - -import org.junit.*; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; - -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.Tag; - - -/** - * @author Francois Beausoleil - */ -public class AuthorizeTagAttributeTests { - //~ Instance fields ================================================================================================ - - private final JspAuthorizeTag authorizeTag = new JspAuthorizeTag(); - - //~ Methods ======================================================================================================== - - @Before - public void setUp() throws Exception { - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", "ROLE_SUPERVISOR", "ROLE_RESTRICTED")); - } - - @After - public void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } - - @Test - public void testAssertsIfAllGrantedSecond() throws JspException { - authorizeTag.setIfAllGranted("ROLE_SUPERVISOR,ROLE_SUPERTELLER"); - authorizeTag.setIfAnyGranted("ROLE_RESTRICTED"); - assertEquals("prevents request - principal is missing ROLE_SUPERTELLER", Tag.SKIP_BODY, - authorizeTag.doStartTag()); - } - - @Test - public void testAssertsIfAnyGrantedLast() throws JspException { - authorizeTag.setIfAnyGranted("ROLE_BANKER"); - assertEquals("prevents request - principal is missing ROLE_BANKER", Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testAssertsIfNotGrantedFirst() throws JspException { - authorizeTag.setIfNotGranted("ROLE_RESTRICTED"); - authorizeTag.setIfAllGranted("ROLE_SUPERVISOR,ROLE_RESTRICTED"); - authorizeTag.setIfAnyGranted("ROLE_SUPERVISOR"); - assertEquals("prevents request - principal has ROLE_RESTRICTED", Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testAssertsIfNotGrantedIgnoresWhitespaceInAttribute() - throws JspException { - authorizeTag.setIfAnyGranted("\tROLE_SUPERVISOR \t, \r\n\t ROLE_TELLER "); - assertEquals("allows request - principal has ROLE_SUPERVISOR", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - @Test - public void testIfAllGrantedIgnoresWhitespaceInAttribute() throws JspException { - authorizeTag.setIfAllGranted("\nROLE_SUPERVISOR\t,ROLE_RESTRICTED\t\n\r "); - assertEquals("allows request - principal has ROLE_RESTRICTED " + "and ROLE_SUPERVISOR", Tag.EVAL_BODY_INCLUDE, - authorizeTag.doStartTag()); - } - - @Test - public void testIfNotGrantedIgnoresWhitespaceInAttribute() throws JspException { - authorizeTag.setIfNotGranted(" \t ROLE_TELLER \r"); - assertEquals("allows request - principal does not have ROLE_TELLER", Tag.EVAL_BODY_INCLUDE, - authorizeTag.doStartTag()); - } -} diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java deleted file mode 100644 index 918d0d39ab..0000000000 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java +++ /dev/null @@ -1,131 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.authz; - -import static org.junit.Assert.*; - -import org.junit.*; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.GrantedAuthorityImpl; -import org.springframework.security.core.context.SecurityContextHolder; - -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.Tag; -import java.util.*; - - - -/** - * - * @author Francois Beausoleil - */ -@SuppressWarnings("deprecation") -public class AuthorizeTagCustomGrantedAuthorityTests { - //~ Instance fields ================================================================================================ - - private final JspAuthorizeTag authorizeTag = new JspAuthorizeTag(); - - //~ Methods ======================================================================================================== - - @Before - public void setUp() { - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", "ROLE_TELLER")); - } - - @After - public void tearDown() { - SecurityContextHolder.clearContext(); - } - - @Test - public void testAllowsRequestWhenCustomAuthorityPresentsCorrectRole() throws JspException { - authorizeTag.setIfAnyGranted("ROLE_TELLER"); - assertEquals("authorized - ROLE_TELLER in both sets", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - @Test - @SuppressWarnings("serial") - public void testRejectsRequestWhenCustomAuthorityReturnsNull() throws JspException { - authorizeTag.setIfAnyGranted("ROLE_TELLER"); - List authorities = new ArrayList(); - authorities.add(new GrantedAuthority() { - public String getAuthority() { - return null; - } - }); - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", authorities)); - - try { - authorizeTag.doStartTag(); - fail("Failed to reject GrantedAuthority with NULL getAuthority()"); - } catch (IllegalArgumentException expected) { - assertTrue("expected", true); - } - } - - @Test - @SuppressWarnings("serial") - public void testAuthorizeCustomGrantedAuthority() throws JspException { - authorizeTag.setIfAnyGranted(null); - authorizeTag.setIfNotGranted(null); - authorizeTag.setIfAllGranted("ROLE_TEST"); - List authorities = new ArrayList(); - authorities.add(new GrantedAuthority() { - public String getAuthority() { - return "ROLE_TEST"; - } - }); - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", authorities)); - assertEquals("Expected to be authorized", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - @Test - @SuppressWarnings("serial") - public void testAuthorizeExtendsGrantedAuthorityImpl() throws JspException { - authorizeTag.setIfAnyGranted(null); - authorizeTag.setIfNotGranted(null); - authorizeTag.setIfAllGranted("ROLE_TEST"); - List authorities = new ArrayList(); - authorities.add(new GrantedAuthorityImpl("ROLE_TEST") {}); - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", authorities)); - assertEquals("Expected to be authorized", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - // SEC-1900 - @Test - public void testAuthorizeUsingGrantedAuthorityImpl() throws JspException { - authorizeTag.setIfAnyGranted(null); - authorizeTag.setIfNotGranted(null); - authorizeTag.setIfAllGranted("ROLE_TEST"); - List authorities = new ArrayList(); - authorities.add(new GrantedAuthorityImpl("ROLE_TEST")); - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", authorities)); - assertEquals("Expected to be authorized", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - // SEC-1900 - @Test - public void testNotAuthorizeUsingGrantedAuthorityImpl() throws JspException { - authorizeTag.setIfAnyGranted(null); - authorizeTag.setIfNotGranted(null); - authorizeTag.setIfAllGranted("ROLE_ADMIN"); - List authorities = new ArrayList(); - authorities.add(new GrantedAuthorityImpl("ROLE_TEST")); - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("abc", "123", authorities)); - assertEquals("Expected to not be authorized", Tag.SKIP_BODY, authorizeTag.doStartTag()); - } -} diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java index 3c1bbcca59..b1fd055ea3 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java @@ -145,77 +145,6 @@ public class AuthorizeTagTests { assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); } - // Legacy attribute tests - - @Test - public void testAlwaysReturnsUnauthorizedIfNoUserFound() throws JspException { - SecurityContextHolder.clearContext(); - authorizeTag.setIfAllGranted("ROLE_TELLER"); - assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testDefaultsToNotOutputtingBodyWhenNoRequiredAuthorities() throws JspException { - assertEquals(null, authorizeTag.getIfAllGranted()); - assertEquals(null, authorizeTag.getIfAnyGranted()); - assertEquals(null, authorizeTag.getIfNotGranted()); - - assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testDefaultsToNotOutputtingBodyWhenNoAuthoritiesProvided() throws JspException { - authorizeTag.setIfAllGranted(""); - authorizeTag.setIfAnyGranted(""); - authorizeTag.setIfNotGranted(""); - - assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testOutputsBodyIfOneRolePresent() throws JspException { - authorizeTag.setIfAnyGranted("ROLE_TELLER"); - assertEquals(Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - @Test - public void testOutputsBodyWhenAllGranted() throws JspException { - authorizeTag.setIfAllGranted("ROLE SUPERVISOR, \nROLE_TELLER"); - assertEquals(Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - @Test - public void testOutputsBodyWhenNotGrantedSatisfied() throws JspException { - authorizeTag.setIfNotGranted("ROLE_BANKER"); - assertEquals(Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag()); - } - - @Test - public void testPreventsBodyOutputIfNoSecurityContext() throws JspException { - SecurityContextHolder.getContext().setAuthentication(null); - authorizeTag.setIfAnyGranted("ROLE_BANKER"); - - assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testSkipsBodyIfNoAnyRolePresent() throws JspException { - authorizeTag.setIfAnyGranted("ROLE_BANKER"); - assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testSkipsBodyWhenMissingAnAllGranted() throws JspException { - authorizeTag.setIfAllGranted("ROLE SUPERVISOR, ROLE_TELLER,\n\rROLE_BANKER"); - assertEquals(Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - - @Test - public void testSkipsBodyWhenNotGrantedUnsatisfied() throws JspException { - authorizeTag.setIfNotGranted("ROLE_TELLER"); - assertEquals("prevents request - principal has ROLE_TELLER", Tag.SKIP_BODY, authorizeTag.doStartTag()); - } - public static class MockWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { public boolean isAllowed(String uri, Authentication authentication) { diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplAttributeTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplAttributeTests.java deleted file mode 100644 index 00868f873e..0000000000 --- a/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplAttributeTests.java +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.velocity; - -import junit.framework.TestCase; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; - -import javax.servlet.jsp.JspException; - - -public class AuthzImplAttributeTests extends TestCase { - //~ Instance fields ================================================================================================ - - private final Authz authz = new AuthzImpl(); - private TestingAuthenticationToken currentUser; - - //~ Methods ======================================================================================================== - - protected void setUp() throws Exception { - SecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("abc", "123", "ROLE_SUPERVISOR","ROLE_RESTRICTED")); - } - - protected void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } - - public void testAssertsIfAllGrantedSecond() { - boolean r1 = authz.allGranted("ROLE_SUPERVISOR,ROLE_SUPERTELLER"); - boolean r2 = authz.anyGranted("ROLE_RESTRICTED"); - - //prevents request - principal is missing ROLE_SUPERTELLE - assertFalse(r1 && r2); - } - - public void testAssertsIfAnyGrantedLast() { - boolean r2 = authz.anyGranted("ROLE_BANKER"); - - // prevents request - principal is missing ROLE_BANKER - assertFalse(r2); - } - - public void testAssertsIfNotGrantedFirst() { - boolean r1 = authz.allGranted("ROLE_SUPERVISOR,ROLE_RESTRICTED"); - boolean r2 = authz.noneGranted("ROLE_RESTRICTED"); - boolean r3 = authz.anyGranted("ROLE_SUPERVISOR"); - - //prevents request - principal has ROLE_RESTRICTED - assertFalse(r1 && r2 && r3); - } - - public void testAssertsIfNotGrantedIgnoresWhitespaceInAttribute() { - //allows request - principal has ROLE_SUPERVISOR - assertTrue(authz.anyGranted("\tROLE_SUPERVISOR \t, \r\n\t ROLE_TELLER ")); - } - - public void testIfAllGrantedIgnoresWhitespaceInAttribute() { - //allows request - principal has ROLE_RESTRICTED and ROLE_SUPERVISOR - assertTrue(authz.allGranted("\nROLE_SUPERVISOR\t,ROLE_RESTRICTED\t\n\r ")); - } - - public void testIfNotGrantedIgnoresWhitespaceInAttribute() - throws JspException { - //prevents request - principal does not have ROLE_TELLER - assertFalse(authz.allGranted(" \t ROLE_TELLER \r")); - } -} diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplAuthorizeTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplAuthorizeTagTests.java deleted file mode 100644 index 53bf646769..0000000000 --- a/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplAuthorizeTagTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.velocity; - -import junit.framework.TestCase; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; - -public class AuthzImplAuthorizeTagTests extends TestCase { - //~ Instance fields ================================================================================================ - - private Authz authz = new AuthzImpl(); - - //~ Methods ======================================================================================================== - - protected void setUp() throws Exception { - SecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("abc", "123", "ROLE_SUPERVISOR", "ROLE_TELLER")); - } - - protected void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } - - public void testAlwaysReturnsUnauthorizedIfNoUserFound() { - SecurityContextHolder.getContext().setAuthentication(null); - - //prevents request - no principal in Context - assertFalse(authz.allGranted("ROLE_TELLER")); - } - - public void testDefaultsToNotOutputtingBodyWhenNoRequiredAuthorities() { - //prevents body output - no authorities granted - assertFalse(authz.allGranted("")); - assertFalse(authz.anyGranted("")); - assertFalse(authz.noneGranted("")); - } - - public void testOutputsBodyIfOneRolePresent() { - //authorized - ROLE_TELLER in both sets - assertTrue(authz.anyGranted("ROLE_TELLER")); - } - - public void testOutputsBodyWhenAllGranted() { - // allows request - all required roles granted on principal - assertTrue(authz.allGranted("ROLE_SUPERVISOR,ROLE_TELLER")); - } - - public void testOutputsBodyWhenNotGrantedSatisfied() { - // allows request - principal doesn't have ROLE_BANKER - assertTrue(authz.noneGranted("ROLE_BANKER")); - } - - public void testPreventsBodyOutputIfNoSecureContext() { - SecurityContextHolder.getContext().setAuthentication(null); - - // prevents output - no context defined - assertFalse(authz.anyGranted("ROLE_BANKER")); - } - - public void testSkipsBodyIfNoAnyRolePresent() { - // unauthorized - ROLE_BANKER not in granted authorities - assertFalse(authz.anyGranted("ROLE_BANKER")); - } - - public void testSkipsBodyWhenMissingAnAllGranted() { - // prevents request - missing ROLE_BANKER on principal - assertFalse(authz.allGranted("ROLE_SUPERVISOR,ROLE_TELLER,ROLE_BANKER")); - } - - public void testSkipsBodyWhenNotGrantedUnsatisfied() { - // prevents request - principal has ROLE_TELLER - assertFalse(authz.noneGranted("ROLE_TELLER")); - } -} diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplTests.java deleted file mode 100644 index f5a79d5cac..0000000000 --- a/taglibs/src/test/java/org/springframework/security/taglibs/velocity/AuthzImplTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * 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.taglibs.velocity; - -import junit.framework.TestCase; - -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.User; - - -public class AuthzImplTests extends TestCase { - //~ Instance fields ================================================================================================ - - private Authz authz = new AuthzImpl(); - - //~ Methods ======================================================================================================== - - public void testOperationWhenPrincipalIsAString() { - Authentication auth = new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES ); - SecurityContextHolder.getContext().setAuthentication(auth); - - assertEquals("rodAsString", authz.getPrincipal()); - } - - public void testOperationWhenPrincipalIsAUserDetailsInstance() { - Authentication auth = new TestingAuthenticationToken(new User("rodUserDetails", "koala", true, true, true, - true, AuthorityUtils.NO_AUTHORITIES), "koala", AuthorityUtils.NO_AUTHORITIES); - SecurityContextHolder.getContext().setAuthentication(auth); - - assertEquals("rodUserDetails", authz.getPrincipal()); - } - - public void testOperationWhenPrincipalIsNull() { - Authentication auth = new TestingAuthenticationToken(null, "koala", AuthorityUtils.NO_AUTHORITIES ); - SecurityContextHolder.getContext().setAuthentication(auth); - - assertNull(authz.getPrincipal()); - } - - public void testOperationWhenSecurityContextIsNull() { - SecurityContextHolder.getContext().setAuthentication(null); - - assertEquals(null, authz.getPrincipal()); - - SecurityContextHolder.getContext().setAuthentication(null); - } -} diff --git a/web/src/main/java/org/springframework/security/web/FilterChainProxy.java b/web/src/main/java/org/springframework/security/web/FilterChainProxy.java index 5944f810cd..60c68bbf7c 100644 --- a/web/src/main/java/org/springframework/security/web/FilterChainProxy.java +++ b/web/src/main/java/org/springframework/security/web/FilterChainProxy.java @@ -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> filterChainMap) { - filterChains = new ArrayList(filterChainMap.size()); - - for (Map.Entry> 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> getFilterChainMap() { - LinkedHashMap> map = new LinkedHashMap>(); - - 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. diff --git a/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java b/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java index 436731f851..bc921fdc1c 100644 --- a/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java +++ b/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java @@ -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 ThrowableAnalyzer which is capable of also unwrapping * ServletExceptions. diff --git a/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java b/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java index 983ce37724..2d22245401 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/ChannelProcessingFilter.java @@ -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"/> diff --git a/web/src/main/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandler.java b/web/src/main/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandler.java index 9a486acc3a..dc5794d5fc 100644 --- a/web/src/main/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandler.java +++ b/web/src/main/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandler.java @@ -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 implements WebSecurityExpressionHandler { +public class DefaultWebSecurityExpressionHandler extends AbstractSecurityExpressionHandler implements SecurityExpressionHandler { private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); diff --git a/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionHandler.java b/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionHandler.java deleted file mode 100644 index f5e350059e..0000000000 --- a/web/src/main/java/org/springframework/security/web/access/expression/WebSecurityExpressionHandler.java +++ /dev/null @@ -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 { - - EvaluationContext createEvaluationContext(Authentication authentication, FilterInvocation invocation); -} diff --git a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java index 02a44562ce..fb62fb05ab 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java @@ -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. *

- * See the {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, Authentication) - * successfulAuthentication} method for more information. + * See the {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} + * method for more information. * *

Authentication Failure

* @@ -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 /j_spring_security_check) - * @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 filterProcessesUrl. */ protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl) { - this.requiresAuthenticationRequestMatcher = new FilterProcessUrlRequestMatcher(defaultFilterProcessesUrl); - this.filterProcessesUrl = defaultFilterProcessesUrl; + setFilterProcessesUrl(defaultFilterProcessesUrl); } /** @@ -178,8 +164,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt *
  • An Authentication 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
  • + * {@link #successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication)} method *
  • An AuthenticationException occurs during authentication. * The {@link #unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException) * unsuccessfulAuthentication} method will be invoked
  • @@ -246,9 +231,7 @@ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilt * Subclasses may override for special requirements, such as Tapestry integration. * * @return true if the filter should attempt authentication, false 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. - *
      - *
    1. Sets the successful Authentication object on the {@link SecurityContextHolder}
    2. - *
    3. Informs the configured RememberMeServices of the successful login
    4. - *
    5. Fires an {@link InteractiveAuthenticationSuccessEvent} via the configured - * ApplicationEventPublisher
    6. - *
    7. Delegates additional behaviour to the {@link AuthenticationSuccessHandler}.
    8. - *
    - * - * @param authResult the object returned from the attemptAuthentication 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 false. */ 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); - } - } } diff --git a/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java index 24dc9ebdef..09e708e680 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java @@ -54,13 +54,6 @@ public class AnonymousAuthenticationFilter extends GenericFilterBean implements private Object principal; private List 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 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 true if the anonymous token should be setup for this request (provided that the request - * doesn't already have some other Authentication inside it), or false 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 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(); - } } diff --git a/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java b/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java index 36687ab9c3..e716618aae 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.java @@ -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 UsernamePasswordAuthenticationFilter 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; } diff --git a/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java index 84542ecfec..359f32a4c1 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java @@ -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; diff --git a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java index da71cfb2ae..55673a3acf 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/logout/LogoutFilter.java @@ -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 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); } } diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.java deleted file mode 100755 index dee974e215..0000000000 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.java +++ /dev/null @@ -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 preAuthenticatedGrantedAuthorities = null; - - public PreAuthenticatedGrantedAuthoritiesAuthenticationDetails(Object context) { - super(context); - } - - /** - * - * @see org.springframework.security.core.authority.GrantedAuthoritiesContainer#getGrantedAuthorities() - */ - public List getGrantedAuthorities() { - Assert.notNull(preAuthenticatedGrantedAuthorities, "Pre-authenticated granted authorities have not been set"); - - return preAuthenticatedGrantedAuthorities; - } - - /** - * @see MutableGrantedAuthoritiesContainer#setGrantedAuthorities(Collection) - */ - public void setGrantedAuthorities(Collection aJ2eeBasedGrantedAuthorities) { - List temp = new ArrayList(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(); - } -} diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsService.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsService.java index 6bc5435e56..d46ed8c37e 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsService.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsService.java @@ -52,19 +52,6 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsService * @param authorities the pre-authenticated authorities. */ protected UserDetails createUserDetails(Authentication token, Collection authorities) { - return createuserDetails(token, authorities); - } - - /** - * Creates the final UserDetails 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 authorities) { return new User(token.getName(), "N/A", true, true, true, true, authorities); } } diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java deleted file mode 100755 index a94cddd9c7..0000000000 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java +++ /dev/null @@ -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; - } -} diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java deleted file mode 100755 index 579ad040f8..0000000000 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java +++ /dev/null @@ -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 getWebSphereGroupsBasedGrantedAuthorities() { - List webSphereGroups = wasHelper.getGroupsForCurrentUser(); - Collection 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; - } - -} diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java index d2db2a46ea..2950d39292 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java @@ -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; } diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java index c06d7208ed..29842544bc 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.java @@ -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; } diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java index bfba4e7905..6d9ae2f1ed 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter.java @@ -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 diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java index 60708dd005..63a90e72c8 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java @@ -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); } diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlStrategy.java deleted file mode 100644 index b1a6399386..0000000000 --- a/web/src/main/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlStrategy.java +++ /dev/null @@ -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 maximumSessions value. - * The {@link SessionRegistry} is used as the source of data on authenticated users and session data. - *

    - * If a user has reached the maximum number of permitted sessions, the behaviour depends on the - * exceptionIfMaxExceeded property. The default behaviour is to expired the least recently used session, which - * will be invalidated by the {@link ConcurrentSessionFilter} if accessed again. If exceptionIfMaxExceeded is - * set to true, however, the user will be prevented from starting a new authenticated session. - *

    - * 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 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 maximumSessions 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 null 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 SessionRegistry for subclass use - * - */ - protected void allowableSessionsExceeded(List 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 exceptionIfMaximumExceeded property, which determines whether the user should be prevented - * from opening more sessions than allowed. If set to true, a SessionAuthenticationException - * will be raised. - * - * @param exceptionIfMaximumExceeded defaults to false. - */ - public void setExceptionIfMaximumExceeded(boolean exceptionIfMaximumExceeded) { - this.exceptionIfMaximumExceeded = exceptionIfMaximumExceeded; - } - - /** - * Sets the maxSessions 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"); - } - } -} diff --git a/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java b/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java index 4ce955afe4..4d38312c3f 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java +++ b/web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionStrategy.java @@ -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 retainedAttributes) { - logger.warn("Retained attributes is deprecated. Override the extractAttributes() method instead."); - Assert.notNull(retainedAttributes); - this.retainedAttributes = retainedAttributes; - } } diff --git a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java index 8a6ba75d19..c33618bf40 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java @@ -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) { diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java index c3dc38afd7..6ea10ee532 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.java @@ -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 authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; diff --git a/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java b/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java index db033ec427..a7b71432c5 100644 --- a/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java +++ b/web/src/main/java/org/springframework/security/web/context/SecurityContextPersistenceFilter.java @@ -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; } diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java index 6087c8756e..93cf6752c0 100644 --- a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java +++ b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java @@ -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; - } - } diff --git a/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java b/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java index 462d271743..8a672f1e91 100644 --- a/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java +++ b/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java @@ -64,18 +64,15 @@ public class ConcurrentSessionFilter extends GenericFilterBean { //~ Methods ======================================================================================================== - - /** - * @deprecated Use constructor which injects the SessionRegistry. - */ - 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; diff --git a/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java b/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java index a2f879e235..906d5c888d 100644 --- a/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java +++ b/web/src/main/java/org/springframework/security/web/session/SessionManagementFilter.java @@ -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. diff --git a/web/src/main/java/org/springframework/security/web/util/AntPathRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/AntPathRequestMatcher.java deleted file mode 100644 index 370241526a..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/AntPathRequestMatcher.java +++ /dev/null @@ -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. - *

    - * 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}. - *

    - *

    - * 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. - *

    - * - * @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) == '/'); - } - } -} diff --git a/web/src/main/java/org/springframework/security/web/util/AnyRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/AnyRequestMatcher.java deleted file mode 100644 index da5d93129f..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/AnyRequestMatcher.java +++ /dev/null @@ -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; - } -} diff --git a/web/src/main/java/org/springframework/security/web/util/ELRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/ELRequestMatcher.java deleted file mode 100644 index 432da20822..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/ELRequestMatcher.java +++ /dev/null @@ -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 - * - *

    With the default EvaluationContext ({@link ELRequestMatcherContext}) you can use - * hasIpAdress() and hasHeader()

    - * - *

    See {@link DelegatingAuthenticationEntryPoint} for an example configuration.

    - * - * - * @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)); - } - -} diff --git a/web/src/main/java/org/springframework/security/web/util/ELRequestMatcherContext.java b/web/src/main/java/org/springframework/security/web/util/ELRequestMatcherContext.java deleted file mode 100644 index ab6fa70e84..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/ELRequestMatcherContext.java +++ /dev/null @@ -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; - } - -} diff --git a/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java b/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java deleted file mode 100644 index 770ccf9396..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java +++ /dev/null @@ -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. - *

    - * 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); - } - } -} diff --git a/web/src/main/java/org/springframework/security/web/util/RegexRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/RegexRequestMatcher.java deleted file mode 100644 index 5e6425ae26..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/RegexRequestMatcher.java +++ /dev/null @@ -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(); - } -} diff --git a/web/src/main/java/org/springframework/security/web/util/RequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/RequestMatcher.java deleted file mode 100644 index 24d96d6c72..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/RequestMatcher.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.springframework.security.web.util; - -import javax.servlet.http.HttpServletRequest; - -/** - * Simple strategy to match an HttpServletRequest. - * - * @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); - -} diff --git a/web/src/main/java/org/springframework/security/web/util/RequestMatcherEditor.java b/web/src/main/java/org/springframework/security/web/util/RequestMatcherEditor.java deleted file mode 100644 index fc1050f7c7..0000000000 --- a/web/src/main/java/org/springframework/security/web/util/RequestMatcherEditor.java +++ /dev/null @@ -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)); - } - -} diff --git a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java index 97425832f6..b67017adc2 100644 --- a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java +++ b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java @@ -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> 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); diff --git a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java index 138943fed0..5ce1ff52c6 100644 --- a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java @@ -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) { diff --git a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java index 43618a2c94..edec9a9264 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java @@ -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 { diff --git a/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java index f7320d897e..e816515ace 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java @@ -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(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java index 58a67669ec..0c33ae491b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DefaultLoginPageGeneratingFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java index 9c64b0071e..9de0ca27ca 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java @@ -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(); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java index f7e0ebd544..81c407fc1a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java index 10f9abd92f..da870255e1 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java @@ -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)); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptorTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptorTests.java deleted file mode 100644 index a526a08771..0000000000 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptorTests.java +++ /dev/null @@ -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())); - } - -} diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java index 2417efc583..34aeb5011e 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java @@ -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; + } } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java index fca4e21885..572355ec12 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServicesTests.java @@ -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; diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java index c8ebe36bd9..a32d189daa 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java @@ -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(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java index 689bcc53c5..2267ea5785 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java @@ -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"); diff --git a/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlStrategyTests.java b/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlStrategyTests.java deleted file mode 100644 index ac591513d1..0000000000 --- a/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlStrategyTests.java +++ /dev/null @@ -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 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); - } -} diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java index e46a44813a..63fcb6688a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java index 1f85a8115a..f05ea1a7dd 100644 --- a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java index ded25f36d6..64a2ff0621 100644 --- a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java @@ -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)); diff --git a/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java b/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java index 00247882ef..e52032430d 100644 --- a/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java @@ -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);

    User: