SEC-2781: Remove deprecations

This commit is contained in:
Rob Winch 2014-12-03 13:34:15 -06:00
parent 5bb0ce9a8f
commit 6e204fff72
177 changed files with 536 additions and 5022 deletions

View File

@ -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<Sid> 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.

View File

@ -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");

View File

@ -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");

View File

@ -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) {

View File

@ -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);

View File

@ -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()));

View File

@ -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

View File

@ -22,6 +22,25 @@
<property name="cacheName" value="aclCache"/>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy">
<constructor-arg>
<bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"/>
</constructor-arg>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
<constructor-arg>
<list>
<bean class="org.springframework.security.core.authority.SimpleGrantedAuthority">
<constructor-arg value="ROLE_USER"/>
</bean>
</list>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy">

View File

@ -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.<AccessDecisionVoter<? extends Object>>asList(voters));
adm = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(voters));
interceptor.setAccessDecisionManager(adm);
interceptor.setAuthenticationManager(authman);
interceptor.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource());

View File

@ -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<CasAssertionAuthenticationToken> authenticationUserDetailsService) {
this.authenticationUserDetailsService = authenticationUserDetailsService;
}

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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<HttpServletRequest,
ServiceAuthenticationDetails>, 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);
}
}
}

View File

@ -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);

View File

@ -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";

View File

@ -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";

View File

@ -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();

View File

@ -52,7 +52,6 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
String alias = element.getAttribute(ATT_ALIAS);
checkForDeprecatedSessionControllerRef(element, pc);
List<BeanMetadataElement> providers = new ManagedList<BeanMetadataElement>();
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 <concurrent-session-control> 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 &lt;http&gt; namespace, such as OpenID, is expected

View File

@ -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");

View File

@ -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<BeanMetadataElement> securityFilterChains = new ManagedList<BeanMetadataElement>();
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();
}
}

View File

@ -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");
}

View File

@ -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());

View File

@ -119,16 +119,13 @@ class LogoutBeanDefinitionParser implements BeanDefinitionParser {
}
private BeanDefinition getLogoutRequestMatcher(String logoutUrl) {
if(this.csrfEnabled) {
BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.util.matcher.AntPathRequestMatcher");
matcherBuilder.addConstructorArgValue(logoutUrl);
if(this.csrfEnabled) {
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<BeanMetadataElement> getLogoutHandlers() {

View File

@ -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<? extends RequestMatcher> 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;
}
}

View File

@ -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 {
}

View File

@ -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}

View File

@ -34,9 +34,9 @@
<xs:attributeGroup name="request-matcher">
<xs:attribute name="request-matcher" use="required">
<xs:annotation>
<xs:documentation>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.
<xs:documentation>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.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
@ -48,20 +48,6 @@
</xs:simpleType>
</xs:attribute>
</xs:attributeGroup>
<xs:attributeGroup name="path-type">
<xs:attribute name="path-type" use="required">
<xs:annotation>
<xs:documentation>Deprecated. Use request-matcher instead.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:enumeration value="ant"/>
<xs:enumeration value="regex"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:attributeGroup>
<xs:attributeGroup name="port">
<xs:attribute name="port" use="required" type="xs:positiveInteger">
<xs:annotation>
@ -1160,9 +1146,9 @@
</xs:attribute>
<xs:attribute name="request-matcher">
<xs:annotation>
<xs:documentation>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.
<xs:documentation>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.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
@ -1173,18 +1159,6 @@
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="path-type">
<xs:annotation>
<xs:documentation>Deprecated. Use request-matcher instead.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:enumeration value="ant"/>
<xs:enumeration value="regex"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="servlet-api-provision" type="xs:boolean">
<xs:annotation>
<xs:documentation>Provides versions of HttpServletRequest security methods such as isUserInRole() and
@ -1228,12 +1202,6 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="access-denied-page" type="xs:token">
<xs:annotation>
<xs:documentation>Deprecated in favour of the access-denied-handler element.
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="disable-url-rewriting" type="xs:boolean">
<xs:annotation>
<xs:documentation>Prevents the jsessionid parameter from being added to rendered URLs.
@ -1534,23 +1502,11 @@
</xs:complexType>
</xs:element>
<xs:attributeGroup name="filter-chain-map.attlist">
<xs:attribute name="path-type">
<xs:annotation>
<xs:documentation>Deprecated. Use request-matcher instead.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:enumeration value="ant"/>
<xs:enumeration value="regex"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="request-matcher">
<xs:annotation>
<xs:documentation>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.
<xs:documentation>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.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
@ -1657,23 +1613,11 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="path-type">
<xs:annotation>
<xs:documentation>Deprecated. Use request-matcher instead.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:enumeration value="ant"/>
<xs:enumeration value="regex"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="request-matcher">
<xs:annotation>
<xs:documentation>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.
<xs:documentation>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.
</xs:documentation>
</xs:annotation>
<xs:simpleType>
@ -1685,26 +1629,6 @@
</xs:simpleType>
</xs:attribute>
</xs:attributeGroup>
<xs:element name="filter-invocation-definition-source">
<xs:annotation>
<xs:documentation>Deprecated synonym for filter-security-metadata-source
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="intercept-url">
<xs:annotation>
<xs:documentation>Specifies the access attributes and/or filter list for a particular set of URLs.
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attributeGroup ref="security:intercept-url.attlist"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attributeGroup ref="security:fsmds.attlist"/>
</xs:complexType>
</xs:element>
<xs:attributeGroup name="http-basic.attlist">
<xs:attribute name="entry-point-ref" type="xs:token">

View File

@ -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)

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -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:

View File

@ -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'
}
}

View File

@ -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();

View File

@ -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'))))
}
}

View File

@ -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'
}
}

View File

@ -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:

View File

@ -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");

View File

@ -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 {
" <b:property name='userPropertyToUse' value='username'/>" +
" </b:bean>" +
" <b:bean id='customUserService' " +
" class='org.springframework.security.core.userdetails.memory.InMemoryDaoImpl'>" +
" <b:property name='userMap' value='bob=f117f0862384e9497ff4f470e3522606,ROLE_A'/>" +
" class='org.springframework.security.provisioning.InMemoryUserDetailsManager'>" +
" <b:constructor-arg>" +
" <b:props>" +
" <b:prop key='bob'>f117f0862384e9497ff4f470e3522606,ROLE_A</b:prop>" +
" </b:props>" +
" </b:constructor-arg>" +
" </b:bean>");
getProvider().authenticate(bob);
}

View File

@ -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");

View File

@ -30,9 +30,9 @@ public class MethodSecurityInterceptorWithAopConfigTests {
static final String ACCESS_MANAGER_XML =
"<b:bean id='accessDecisionManager' class='org.springframework.security.access.vote.AffirmativeBased'>" +
" <b:property name='decisionVoters'>" +
" <b:constructor-arg>" +
" <b:list><b:bean class='org.springframework.security.access.vote.RoleVoter'/></b:list>" +
" </b:property>" +
" </b:constructor-arg>" +
"</b:bean>";
static final String TARGET_BEAN_AND_INTERCEPTOR =

View File

@ -104,7 +104,7 @@
<bean id="fcv" class="org.springframework.security.config.http.DefaultFilterChainValidator" />
<bean id="newFilterChainProxyRegex" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="regex">
<sec:filter-chain-map request-matcher="regex">
<sec:filter-chain pattern="\A/foo/.*\Z" filters="mockFilter"/>
<sec:filter-chain pattern="\A/s[oO]me/other/path/.*\Z" filters="sif,mockFilter,mockFilter2"/>
<sec:filter-chain pattern="\A/do/not/filter\Z" filters="none"/>

View File

@ -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 <tt>List&lt;ConfigAttribute&gt;</tt> from a comma separated list of values.
* <p>
* 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);
}
}
}

View File

@ -66,14 +66,6 @@ public class SecurityConfig implements ConfigAttribute {
return createList(StringUtils.commaDelimitedListToStringArray(access));
}
/**
* @deprecated Use createList instead
*/
@Deprecated
public static List<ConfigAttribute> createSingleAttributeList(String access) {
return createList(access);
}
public static List<ConfigAttribute> createList(String... attributeNames) {
Assert.notNull(attributeNames, "You must supply an array of attribute names");
List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(attributeNames.length);

View File

@ -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 <tt>UserDetailsService</tt> in a way that its <tt>loadUserByUsername()</tt>
* method returns wrapped <tt>UserDetails</tt> 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;
}
}

View File

@ -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 <tt>UserDetails</tt> in a way that its <tt>getAuthorities()</tt> method is
* delegated to <tt>RoleHierarchy.getReachableGrantedAuthorities</tt>. All other methods are
* delegated to the <tt>UserDetails</tt> 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<? extends GrantedAuthority> 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;
}
}

View File

@ -50,9 +50,6 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
private boolean allowIfAllAbstainDecisions = false;
protected AbstractAccessDecisionManager() {
}
protected AbstractAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> 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<AccessDecisionVoter<? extends Object>> newList) {
Assert.notEmpty(newList);
Iterator<AccessDecisionVoter<? extends Object>> 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);
}

View File

@ -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<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
}

View File

@ -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<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
}

View File

@ -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<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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"));
}
}
}

View File

@ -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);

View File

@ -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();
}
}

View File

@ -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}.
* <p>
* By default will create an instance of <code>AuthenticationDetails</code>.
* Any object that accepts an <code>Object</code> as its sole constructor can
* be used instead of this default.
* </p>
*
* @author Ruud Senden
* @since 2.0
* @deprecated Write an implementation of AuthenticationDetailsSource which returns the desired type directly.
*/
@Deprecated
public class AuthenticationDetailsSourceImpl implements AuthenticationDetailsSource<Object, Object> {
//~ 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;
}
}

View File

@ -36,11 +36,6 @@ public class BadCredentialsException extends AuthenticationException {
super(msg);
}
@Deprecated
public BadCredentialsException(String msg, Object extraInformation) {
super(msg, extraInformation);
}
/**
* Constructs a <code>BadCredentialsException</code> with the specified
* message and root cause.

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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<AuthenticationProvider> 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) {}

View File

@ -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);
}

View File

@ -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"));
}
}
}

View File

@ -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"));
}
}

View File

@ -32,7 +32,6 @@ import java.util.List;
public final class DelegatingApplicationListener implements ApplicationListener<ApplicationEvent> {
private List<SmartApplicationListener> listeners = new ArrayList<SmartApplicationListener>();
@Override
public void onApplicationEvent(ApplicationEvent event) {
if(event == null) {
return;

View File

@ -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;
}
}

View File

@ -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<GrantedAuthority> authorities;
public void setGrantedAuthorities(Collection<? extends GrantedAuthority> newAuthorities) {
ArrayList<GrantedAuthority> temp = new ArrayList<GrantedAuthority>(newAuthorities.size());
temp.addAll(newAuthorities);
authorities = Collections.unmodifiableList(temp);
}
public List<GrantedAuthority> 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();
}
}

View File

@ -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}.
*
* <p>
* Stores a <code>String</code> 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;
}
}

View File

@ -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.
* <p>
* 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<? extends GrantedAuthority> authorities);
}

View File

@ -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.
* <p>
* Used to extract the session ID from an <code>Authentication</code> 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 <code>null</code> if not known.
*/
String getSessionId();
}

View File

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

View File

@ -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);

View File

@ -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 <code>UserMap</code> to reflect the <code>Properties</code> instance passed. This
* helps externalise user information to another file etc.
*
* @param props the account information in a <code>Properties</code> object format
*/
public void setUserProperties(Properties props) {
UserMap userMap = new UserMap();
this.userMap = UserMapEditor.addUsersFromProperties(userMap, props);
}
}

View File

@ -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.
* <p>
* 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<String, UserDetails> userMap = new HashMap<String, UserDetails>();
//~ 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} &lt;{@link String}, {@link UserDetails}> with pairs (username, userdetails)
* @since 1.1
*/
public void setUsers(Map<String, UserDetails> users) {
userMap.clear();
for (Map.Entry<String, UserDetails> entry : users.entrySet()) {
userMap.put(entry.getKey().toLowerCase(), entry.getValue());
}
}
}

View File

@ -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}.<p>The format of entries should be:</p>
* <p><code> username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] </code></p>
* <p>The <code>password</code> must always be the first entry after the equals. The <code>enabled</code> or
* <code>disabled</code> keyword can appear anywhere (apart from the first entry reserved for the password). If
* neither <code>enabled</code> or <code>disabled</code> appear, the default is <code>enabled</code>. At least one
* granted authority must be listed.</p>
* <p>The <code>username</code> represents the key and duplicates are handled the same was as duplicates would be
* in Java <code>Properties</code> files.</p>
* <p>If the above requirements are not met, the invalid entry will be silently ignored.</p>
* <p>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.</p>
*
* @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);
}
}

View File

@ -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);
}
}

View File

@ -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<GrantedAuthority> 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<GrantedAuthority> 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);
}
}

View File

@ -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<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
}
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
}
}

View File

@ -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.<AccessDecisionVoter<? extends Object>>asList(grant, deny, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, deny, abstain));
mgr.afterPropertiesSet();
mgr.decide(user, new Object(), attrs);
}
@Test
public void oneDenyVoteOneAbstainVoteOneAffirmativeVoteGrantsAccess() throws Exception {
mgr.setDecisionVoters(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, grant));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, grant));
mgr.decide(user, new Object(), attrs);
}
@Test
public void oneAffirmativeVoteTwoAbstainVotesGrantsAccess() throws Exception {
mgr.setDecisionVoters(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, abstain, abstain));
mgr.decide(user, new Object(), attrs);
}
@Test(expected=AccessDeniedException.class)
public void oneDenyVoteTwoAbstainVotesDeniesAccess() throws Exception {
mgr.setDecisionVoters(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, abstain));
mgr.decide(user, new Object(), attrs);
}
@Test(expected=AccessDeniedException.class)
public void onlyAbstainVotesDeniesAccessWithDefault() throws Exception {
mgr.setDecisionVoters(Arrays.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>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.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
mgr.setAllowIfAllAbstainDecisions(true);
assertTrue(mgr.isAllowIfAllAbstainDecisions()); // check changed

View File

@ -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() {

View File

@ -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() {

View File

@ -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();
}
}

View File

@ -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);
}

View File

@ -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<Object> providers = new ArrayList<Object>();
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);
}

View File

@ -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));
}

View File

@ -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);

View File

@ -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));
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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);
}
}
}

View File

@ -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
<property name="accessDecisionManager" ref="accessDecisionManager"/>
<property name="runAsManager" ref="runAsManager"/>
<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/super/.*\Z" access="ROLE_WE_DONT_HAVE"/>
<security:intercept-url pattern="\A/secure/.*\" access="ROLE_SUPERVISOR,ROLE_TELLER"/>
</security:filter-security-metadata-source>
@ -6488,11 +6488,6 @@ The attributes on the `<http>` 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 <<nsa-access-denied-handler,access-denied-handler>> 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-request-matcher,request-matcher>>.
[[nsa-http-pattern]]
* **pattern**
Defining a pattern for the <<nsa-http,http>> element controls the requests which will be filtered through the list of filters which it defines. The interpretation is dependent on the configured <<nsa-http-request-matcher,request-matcher>>. 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 <intercept-url>
* <<nsa-filter-invocation-definition-source,filter-invocation-definition-source>>
* <<nsa-filter-security-metadata-source,filter-security-metadata-source>>
* <<nsa-http,http>>
@ -7603,14 +7592,9 @@ Used to explicitly configure a FilterChainProxy instance with a FilterChainMap
===== <filter-chain-map> Attributes
[[nsa-filter-chain-map-path-type]]
* **path-type**
Superseded by the <<nsa-filter-chain-map-request-matcher,request-matcher>> 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 <<nsa-filter-chain
A reference to a `RequestMatcher` that will be used to determine if the `Filter`'s from the `filters` attribute should be invoked.
[[nsa-filter-invocation-definition-source]]
==== <filter-invocation-definition-source>
Deprecated synonym for filter-security-metadata-source
[[nsa-filter-invocation-definition-source-attributes]]
===== <filter-invocation-definition-source> 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>>
[[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 <intercept-url> 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 <filter-invocation-definition-source>
* <<nsa-intercept-url,intercept-url>>
[[nsa-filter-security-metadata-source]]
==== <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<http> 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>>
[[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]]

View File

@ -11,25 +11,25 @@
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<bean id="fcpMinimalStack" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain-map request-matcher="ant">
<sec:filter-chain pattern="/**" filters="scpf,preAuthFilter,etf,fsi"/>
</sec:filter-chain-map>
</bean>
<bean id="fcpFullStack" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain-map request-matcher="ant">
<sec:filter-chain pattern="/**" filters="scpf,preAuthFilter,apf,basicPf,logoutFilter,scharf,etf,fsi"/>
</sec:filter-chain-map>
</bean>
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<constructor-arg>
<list>
<bean class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userService"/>
</bean>
</list>
</property>
</constructor-arg>
</bean>
<sec:user-service id="userService">
@ -43,8 +43,7 @@
</bean>
<bean id="basicPf" class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="ignoreFailure" value="true"/>
<constructor-arg ref="authenticationManager"/>
</bean>
<bean id="preAuthFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
@ -67,7 +66,7 @@
</bean>
<bean id="etf" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<property name="authenticationEntryPoint" ref="preAuthenticatedProcessingFilterEntryPoint"/>
<constructor-arg ref="preAuthenticatedProcessingFilterEntryPoint"/>
</bean>
<bean id="preAuthenticatedAuthenticationProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
@ -79,12 +78,12 @@
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<constructor-arg>
<list>
<ref bean="roleVoter"/>
<bean class="org.springframework.security.access.vote.RoleVoter"/>
</list>
</property>
</constructor-arg>
<property name="allowIfAllAbstainDecisions" value="false"/>
</bean>
<bean id="fsi" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">

View File

@ -31,12 +31,12 @@
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<constructor-arg>
<list>
<bean class="org.springframework.security.access.vote.RoleVoter"/>
</list>
</property>
</constructor-arg>
<property name="allowIfAllAbstainDecisions" value="false"/>
</bean>
<sec:authentication-manager alias="authenticationManager">

View File

@ -16,13 +16,13 @@
</security:authentication-manager>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<constructor-arg>
<util:list>
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</util:list>
</property>
</constructor-arg>
<property name="allowIfAllAbstainDecisions" value="false"/>
</bean>
<bean id="securityInterceptor" class="org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor">

View File

@ -21,7 +21,7 @@
</http>
<beans:bean id="aep" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login.jsp" />
<beans:constructor-arg value="/login.jsp" />
</beans:bean>
<beans:bean id="myAuthFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
@ -30,8 +30,8 @@
</beans:bean>
<beans:bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
<beans:property name="sessionRegistry" ref="sessionRegistry" />
<beans:property name="expiredUrl" value="/session-expired.htm" />
<beans:constructor-arg ref="sessionRegistry" />
<beans:constructor-arg value="/session-expired.htm" />
</beans:bean>
<beans:bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">

View File

@ -60,35 +60,6 @@
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<description>
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.
</description>
<name>ifNotGranted</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>
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.
</description>
<name>ifAllGranted</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>
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.
</description>
<name>ifAnyGranted</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>

View File

@ -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()) {

View File

@ -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);
}

View File

@ -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;

View File

@ -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".
* <p>
* 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.
* <p>
* The single-level search is performed by default. Setting the <tt>searchSubTree</tt> property to true will enable
* a search of the entire subtree under <tt>groupSearchBase</tt>.
*
@ -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 <tt>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;

View File

@ -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<OpenIDAttribute> attributes) throws ConsumerException {
this(new ConsumerManager(), attributes);
}
@Deprecated
public OpenID4JavaConsumer(ConsumerManager consumerManager, final List<OpenIDAttribute> attributes)
throws ConsumerException {
this.consumerManager = consumerManager;
this.attributesToFetchFactory = new AxFetchListFactory() {
private final List<OpenIDAttribute> fetchAttrs = Collections.unmodifiableList(attributes);
public List<OpenIDAttribute> createAttributeList(String identifier) {
return fetchAttrs;
}
};
}
public OpenID4JavaConsumer(AxFetchListFactory attributesToFetchFactory) throws ConsumerException {
this(new ConsumerManager(), attributesToFetchFactory);
}

Some files were not shown because too many files have changed in this diff Show More