1
0
mirror of synced 2026-08-04 09:17:02 +00:00

Polish GrantedAuthorityDefaults

* Move GrantedAuthorityDefaults to config module
* Move setting of default role into config module vs
  ApplicationContextAware

Issue gh-3701
This commit is contained in:
Rob Winch
2016-09-22 15:13:05 -05:00
parent eabeaf35d6
commit b443baef04
24 changed files with 685 additions and 336 deletions
@@ -23,11 +23,11 @@ import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
import org.springframework.security.config.GrantedAuthorityDefaults;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder;
import org.springframework.security.config.annotation.web.configurers.ChannelSecurityConfigurer;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
@@ -61,7 +61,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
private String groupRoleAttribute = "cn";
private String groupSearchBase = "";
private String groupSearchFilter = "(uniqueMember={0})";
private GrantedAuthorityDefaults rolePrefix = new GrantedAuthorityDefaults("ROLE_");
private String rolePrefix = "ROLE_";
private String userSearchBase = ""; // only for search
private String userSearchFilter = null;// "uid={0}"; // only for search
private String[] userDnPatterns;
@@ -129,7 +129,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
contextSource, groupSearchBase);
defaultAuthoritiesPopulator.setGroupRoleAttribute(groupRoleAttribute);
defaultAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix.getRolePrefix());
defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix);
this.ldapAuthoritiesPopulator = defaultAuthoritiesPopulator;
return defaultAuthoritiesPopulator;
@@ -162,7 +162,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
}
SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
simpleAuthorityMapper.setPrefix(this.rolePrefix.getRolePrefix());
simpleAuthorityMapper.setPrefix(this.rolePrefix);
simpleAuthorityMapper.afterPropertiesSet();
this.authoritiesMapper = simpleAuthorityMapper;
return simpleAuthorityMapper;
@@ -357,7 +357,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
* @see SimpleAuthorityMapper#setPrefix(String)
*/
public LdapAuthenticationProviderConfigurer<B> rolePrefix(String rolePrefix) {
this.rolePrefix = new GrantedAuthorityDefaults(rolePrefix);
this.rolePrefix = rolePrefix;
return this;
}
@@ -616,4 +616,4 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
return new PasswordCompareConfigurer().passwordAttribute("password")
.passwordEncoder(new PlaintextPasswordEncoder());
}
}
}
@@ -64,11 +64,10 @@ import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.config.GrantedAuthorityDefaults;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.util.Assert;
/**
@@ -134,14 +133,6 @@ public class GlobalMethodSecurityConfiguration
.setSecurityMetadataSource(methodSecurityMetadataSource());
RunAsManager runAsManager = runAsManager();
if (runAsManager != null) {
if (runAsManager instanceof RunAsManagerImpl) {
GrantedAuthorityDefaults grantedAuthorityDefaults =
getSingleBeanOrNull(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaults != null) {
((RunAsManagerImpl) runAsManager).setRolePrefix(
grantedAuthorityDefaults.getRolePrefix());
}
}
methodSecurityInterceptor.setRunAsManager(runAsManager);
}
@@ -31,6 +31,7 @@ import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource;
@@ -216,6 +217,11 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
if(roleHiearchyBeanNames.length == 1) {
defaultHandler.setRoleHierarchy(context.getBean(roleHiearchyBeanNames[0], RoleHierarchy.class));
}
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
defaultHandler.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
}
expressionHandler = postProcess(defaultHandler);
@@ -19,10 +19,12 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -91,7 +93,15 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>> extend
if (trustResolver != null) {
securityContextRequestFilter.setTrustResolver(trustResolver);
}
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if(context != null) {
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
}
}
securityContextRequestFilter = postProcess(securityContextRequestFilter);
http.addFilter(securityContextRequestFilter);
}
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.core;
import org.springframework.security.core.GrantedAuthority;
/**
* Allows providing defaults for {@link GrantedAuthority}
*
* @author Eddú Meléndez
* @since 4.2.0
*/
public final class GrantedAuthorityDefaults {
private final String rolePrefix;
public GrantedAuthorityDefaults(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
/**
* The default prefix used with role based authorization. Default is "ROLE_".
*
* @return the default role prefix
*/
public String getRolePrefix() {
return this.rolePrefix;
}
}
@@ -15,8 +15,12 @@
*/
package org.springframework.security.config.http;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
@@ -33,9 +37,6 @@ import org.springframework.security.web.access.intercept.DefaultFilterInvocation
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import java.util.List;
/**
* Allows for convenient creation of a {@link FilterInvocationSecurityMetadataSource} bean
@@ -133,8 +134,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
}
static String registerDefaultExpressionHandler(ParserContext pc) {
BeanDefinition expressionHandler = BeanDefinitionBuilder.rootBeanDefinition(
DefaultWebSecurityExpressionHandler.class).getBeanDefinition();
BeanDefinition expressionHandler = GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, DefaultWebSecurityExpressionHandlerBeanFactory.class);
String expressionHandlerRef = pc.getReaderContext().generateBeanName(
expressionHandler);
pc.registerBeanComponent(new BeanComponentDefinition(expressionHandler,
@@ -223,4 +223,12 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
return filterInvocationDefinitionMap;
}
static class DefaultWebSecurityExpressionHandlerBeanFactory extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
public DefaultWebSecurityExpressionHandler getBean() {
handler.setDefaultRolePrefix(this.rolePrefix);
return handler;
}
}
}
@@ -0,0 +1,61 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.http;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
/**
* @author Rob Winch
* @since 4.2
*/
class GrantedAuthorityDefaultsParserUtils {
static RootBeanDefinition registerWithDefaultRolePrefix(ParserContext pc, Class<? extends AbstractGrantedAuthorityDefaultsBeanFactory> beanFactoryClass) {
RootBeanDefinition beanFactoryDefinition = new RootBeanDefinition(beanFactoryClass);
String beanFactoryRef = pc.getReaderContext().generateBeanName(beanFactoryDefinition);
pc.getRegistry().registerBeanDefinition(beanFactoryRef, beanFactoryDefinition);
RootBeanDefinition bean = new RootBeanDefinition();
bean.setFactoryBeanName(beanFactoryRef);
bean.setFactoryMethodName("getBean");
return bean;
}
static abstract class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
}
}
abstract Object getBean();
}
private GrantedAuthorityDefaultsParserUtils() {}
}
@@ -18,9 +18,12 @@ package org.springframework.security.config.http;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.w3c.dom.Element;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanReference;
@@ -37,6 +40,7 @@ import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.config.Elements;
import org.springframework.security.config.http.GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl;
@@ -65,17 +69,30 @@ import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.*;
import static org.springframework.security.config.http.SecurityFilters.*;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_FILTERS;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_HTTP_METHOD;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN;
import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL;
import static org.springframework.security.config.http.SecurityFilters.CHANNEL_FILTER;
import static org.springframework.security.config.http.SecurityFilters.CONCURRENT_SESSION_FILTER;
import static org.springframework.security.config.http.SecurityFilters.CORS_FILTER;
import static org.springframework.security.config.http.SecurityFilters.CSRF_FILTER;
import static org.springframework.security.config.http.SecurityFilters.FILTER_SECURITY_INTERCEPTOR;
import static org.springframework.security.config.http.SecurityFilters.HEADERS_FILTER;
import static org.springframework.security.config.http.SecurityFilters.JAAS_API_SUPPORT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.REQUEST_CACHE_FILTER;
import static org.springframework.security.config.http.SecurityFilters.SECURITY_CONTEXT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.SERVLET_API_SUPPORT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.SESSION_MANAGEMENT_FILTER;
import static org.springframework.security.config.http.SecurityFilters.WEB_ASYNC_MANAGER_FILTER;
/**
* Stateful class which helps HttpSecurityBDP to create the configuration for the
@@ -543,8 +560,7 @@ class HttpConfigurationBuilder {
}
if ("true".equals(provideServletApi)) {
servApiFilter = new RootBeanDefinition(
SecurityContextHolderAwareRequestFilter.class);
servApiFilter = GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, SecurityContextHolderAwareRequestFilterBeanFactory.class);
servApiFilter.getPropertyValues().add("authenticationManager",
authenticationManager);
}
@@ -715,7 +731,7 @@ class HttpConfigurationBuilder {
voters.add(expressionVoter.getBeanDefinition());
}
else {
voters.add(new RootBeanDefinition(RoleVoter.class));
voters.add(GrantedAuthorityDefaultsParserUtils.registerWithDefaultRolePrefix(pc, RoleVoterBeanFactory.class));
voters.add(new RootBeanDefinition(AuthenticatedVoter.class));
}
accessDecisionMgr = new RootBeanDefinition(AffirmativeBased.class);
@@ -852,4 +868,22 @@ class HttpConfigurationBuilder {
return filters;
}
static class RoleVoterBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private RoleVoter voter = new RoleVoter();
public RoleVoter getBean() {
voter.setRolePrefix(this.rolePrefix);
return voter;
}
}
static class SecurityContextHolderAwareRequestFilterBeanFactory extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
public SecurityContextHolderAwareRequestFilter getBean() {
filter.setRolePrefix(this.rolePrefix);
return filter;
}
}
}
@@ -45,6 +45,8 @@ import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource;
@@ -71,6 +73,7 @@ import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.Elements;
import org.springframework.security.config.authentication.AuthenticationManagerFactoryBean;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.Assert;
@@ -198,8 +201,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
expressionHandlerRef));
}
else {
BeanDefinition expressionHandler = new RootBeanDefinition(
DefaultMethodSecurityExpressionHandler.class);
RootBeanDefinition expressionHandler = registerWithDefaultRolePrefix(pc, DefaultMethodSecurityExpressionHandlerBeanFactory.class);
expressionHandlerRef = pc.getReaderContext().generateBeanName(
expressionHandler);
pc.registerBeanComponent(new BeanComponentDefinition(
@@ -240,8 +243,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
}
if (jsr250Enabled) {
delegates.add(BeanDefinitionBuilder.rootBeanDefinition(
Jsr250MethodSecurityMetadataSource.class).getBeanDefinition());
RootBeanDefinition jsrMetadataSource = registerWithDefaultRolePrefix(pc, Jsr250MethodSecurityMetadataSourceBeanFactory.class);
delegates.add(jsrMetadataSource);
}
// Now create a Map<String, ConfigAttribute> for each <protect-pointcut>
@@ -474,6 +477,17 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
BeanIds.METHOD_SECURITY_METADATA_SOURCE_ADVISOR, advisor);
}
private RootBeanDefinition registerWithDefaultRolePrefix(ParserContext pc, Class<? extends AbstractGrantedAuthorityDefaultsBeanFactory> beanFactoryClass) {
RootBeanDefinition beanFactoryDefinition = new RootBeanDefinition(beanFactoryClass);
String beanFactoryRef = pc.getReaderContext().generateBeanName(beanFactoryDefinition);
pc.getRegistry().registerBeanDefinition(beanFactoryRef, beanFactoryDefinition);
RootBeanDefinition bean = new RootBeanDefinition();
bean.setFactoryBeanName(beanFactoryRef);
bean.setFactoryMethodName("getBean");
return bean;
}
/**
* Delays the lookup of the AuthenticationManager within MethodSecurityInterceptor, to
* prevent issues like SEC-933.
@@ -522,6 +536,38 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
}
}
static class Jsr250MethodSecurityMetadataSourceBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private Jsr250MethodSecurityMetadataSource source = new Jsr250MethodSecurityMetadataSource();
public Jsr250MethodSecurityMetadataSource getBean() {
source.setDefaultRolePrefix(this.rolePrefix);
return source;
}
}
static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
public DefaultMethodSecurityExpressionHandler getBean() {
handler.setDefaultRolePrefix(this.rolePrefix);
return handler;
}
}
static abstract class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
String[] grantedAuthorityDefaultsBeanNames = applicationContext.getBeanNamesForType(GrantedAuthorityDefaults.class);
if(grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = applicationContext.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
this.rolePrefix = grantedAuthorityDefaults.getRolePrefix();
}
}
}
/**
* Delays setting a bean of a given name to be lazyily initialized until after all the
* beans are registered.
@@ -18,7 +18,6 @@ package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl
import org.springframework.security.config.GrantedAuthorityDefaults;
import java.lang.reflect.Proxy;
@@ -28,6 +27,7 @@ import org.springframework.beans.factory.config.BeanPostProcessor
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter
import org.springframework.security.config.annotation.method.configuration.NamespaceGlobalMethodSecurityTests.BaseMethodConfig;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import javax.sql.DataSource
@@ -17,7 +17,6 @@ package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor
import org.springframework.security.config.GrantedAuthorityDefaults
import static org.assertj.core.api.Assertions.assertThat
import static org.junit.Assert.fail
@@ -50,7 +49,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.authentication.BaseAuthenticationConfig;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
@@ -148,39 +147,6 @@ public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
public static class Jsr250Config extends BaseMethodConfig {
}
def "enable jsr250 with custom role prefix"() {
when:
context = new AnnotationConfigApplicationContext(Jsr250WithCustomRolePrefixConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then: "@Secured and @PreAuthorize are ignored"
service.secured() == null
service.preAuthorize() == null
when: "@DenyAll method invoked"
service.jsr250()
then: "access is denied"
thrown(AccessDeniedException)
when: "@PermitAll method invoked"
String jsr250PermitAll = service.jsr250PermitAll()
then: "access is allowed"
jsr250PermitAll == null
when:
Jsr250MethodSecurityMetadataSource jsr250MethodSecurity = context.getBean(Jsr250MethodSecurityMetadataSource)
then:
jsr250MethodSecurity.defaultRolePrefix == "ROLE:"
}
@EnableGlobalMethodSecurity(jsr250Enabled = true)
@Configuration
public static class Jsr250WithCustomRolePrefixConfig extends BaseMethodConfig {
@Bean
public GrantedAuthorityDefaults ga() {
return new GrantedAuthorityDefaults("ROLE:")
}
}
// --- metadata-source-ref ---
def "custom MethodSecurityMetadataSource can be used with higher priority than other sources"() {
@@ -355,7 +321,7 @@ public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
context = new AnnotationConfigApplicationContext(BaseMethodConfig,CustomRunAsManagerConfig)
MethodSecurityService service = context.getBean(MethodSecurityService)
then:
service.runAs().authorities.find { it.authority == "ROLE:RUN_AS_SUPER"}
service.runAs().authorities.find { it.authority == "ROLE_RUN_AS_SUPER"}
}
@EnableGlobalMethodSecurity(securedEnabled = true)
@@ -366,11 +332,6 @@ public class NamespaceGlobalMethodSecurityTests extends BaseSpringSpec {
runAsManager.setKey("some key")
return runAsManager
}
@Bean
public GrantedAuthorityDefaults ga() {
return new GrantedAuthorityDefaults("ROLE:")
}
}
// --- secured-annotation ---
@@ -0,0 +1,183 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.core;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class GrantedAuthorityDefaultsJcTests {
@Autowired
FilterChainProxy springSecurityFilterChain;
@Autowired
MessageService messageService;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockFilterChain chain;
@Before
public void setup() {
setup("USER");
request = new MockHttpServletRequest();
request.setMethod("GET");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void doFilter() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void doFilterDenied() throws Exception {
setup("DENIED");
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void message() {
messageService.getMessage();
}
@Test
public void jsrMessage() {
messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
public void messageDenied() {
setup("DENIED");
messageService.getMessage();
}
@Test(expected = AccessDeniedException.class)
public void jsrMessageDenied() {
setup("DENIED");
messageService.getJsrMessage();
}
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
assertThat(httpRequest.isUserInRole("USER")).isTrue();
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
super.doFilter(request, response);
}
};
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
private void setup(String role) {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", role);
SecurityContextHolder.getContext().setAuthentication(user);
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, jsr250Enabled=true)
static class Config extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().access("hasRole('USER')");
}
@Bean
public MessageService messageService() {
return new HelloWorldMessageService();
}
@Bean
public static GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults("");
}
}
}
@@ -0,0 +1,146 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.core;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class GrantedAuthorityDefaultsXmlTests {
@Autowired
FilterChainProxy springSecurityFilterChain;
@Autowired
MessageService messageService;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockFilterChain chain;
@Before
public void setup() {
setup("USER");
request = new MockHttpServletRequest();
request.setMethod("GET");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void doFilter() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void doFilterDenied() throws Exception {
setup("DENIED");
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void message() {
messageService.getMessage();
}
@Test
public void jsrMessage() {
messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
public void messageDenied() {
setup("DENIED");
messageService.getMessage();
}
@Test(expected = AccessDeniedException.class)
public void jsrMessageDenied() {
setup("DENIED");
messageService.getJsrMessage();
}
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
assertThat(httpRequest.isUserInRole("USER")).isTrue();
assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
super.doFilter(request, response);
}
};
springSecurityFilterChain.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
private void setup(String role) {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", role);
SecurityContextHolder.getContext().setAuthentication(user);
}
}
@@ -0,0 +1,36 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.core;
import javax.annotation.security.RolesAllowed;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* @author Rob Winch
*/
public class HelloWorldMessageService implements MessageService {
@PreAuthorize("hasRole('USER')")
public String getMessage() {
return "Hello World";
}
@RolesAllowed("USER")
public String getJsrMessage() {
return "Hello JSR";
}
}
@@ -0,0 +1,24 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.core;
/**
* @author Rob Winch
*/
public interface MessageService {
String getMessage();
String getJsrMessage();
}
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/security"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<http use-expressions="true">
<intercept-url access="hasRole('USER')" pattern="/**" />
<form-login/>
<logout/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="password" authorities="USER"/>
<user name="admin" password="password" authorities="USER,ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
<global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled"/>
<b:bean class="org.springframework.security.config.core.HelloWorldMessageService"/>
<b:bean class="org.springframework.security.config.core.GrantedAuthorityDefaults"
c:rolePrefix=""/>
</b:beans>