在使用Oauth2和spring安全性进行集成测试时遇到麻烦...在将Oauth2配置添加到代码库集成测试之前正常工作
设定:
工作流:
问题: 我可以启动系统和功能正常但现在我的集成测试甚至无法启动它抱怨无法创建应用程序上下文
一些配置代码:
@Configuration
@RequiredArgsConstructor
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@NonNull
private final MethodSecurityConfig methodSecurityConfig;
private static final String AUTH_LOGIN_URL = "/auth/login";
private static final String AUTH_DENIED_URL = "/auth/denied";
private static final String AUTH_LOGOUT_URL = "/auth/logout";
private static final String AUTH_CHECK_URL = "/auth/check";
private static final String ASC_URL = "some auth server url";
@Override
protected void configure(final HttpSecurity http) throws Exception {
//@formatter:off
http.sessionManagement()... // resource restrictions here
//@formatter:on
}
@Bean
public AccessDecisionManager accessDecisionManager() {
final List<AccessDecisionVoter<?>> voters = new ArrayList<>();
voters.add(new WebExpressionVoter());
return new AffirmativeBased(voters);
}
@Bean
public AuthenticationSuccessHandler loginSuccessHandler() {
val handler = new SafeRedirectRequestAwareAuthenticationSuccessHandler();
handler.setTargetUrlParameter("redirect");
return handler;
}
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
val handler = new SimpleUrlLogoutSuccessHandler();
handler.setDefaultTargetUrl(ASC_URL + "/logout");
handler.setAlwaysUseDefaultTargetUrl(true);
return handler;
}
@Bean
public PrincipalExtractor principalExtractor() {
return new WebAdminPrincipalExtractor();
}
@Bean
public AuthoritiesExtractor authoritiesExtractor() {
return new WebAdminAuthoritiesExtractor();
}
}
Oauth2配置:
@Configuration
@Import({ OAuth2AuthorizationServerConfiguration.class,
OAuth2ResourceServerConfiguration.class,
OAuth2RestOperationsConfiguration.class })
@EnableConfigurationProperties(OAuth2ClientProperties.class)
public class OAuth2Configuration {
private final OAuth2ClientProperties credentials;
public OAuth2Configuration(OAuth2ClientProperties credentials) {
this.credentials = credentials;
}
@Bean
public ResourceServerProperties resourceServerProperties() {
return new ResourceServerProperties(this.credentials.getClientId(),
this.credentials.getClientSecret());
}
}
自定义安全逻辑:
public class WebAdminAuthoritiesExtractor implements AuthoritiesExtractor {
@Autowired
AccountRepository accountRepository;
@Autowired
RoleHierarchy roleHierarchy;
@Override
public List<GrantedAuthority> extractAuthorities(final Map<String, Object> map) {
val account = accountRepository.findByEmailIgnoreCase((String) map.get("email"));
final List<String> permissions = new ArrayList<>();
// Individual permissions from the account.
if (account.getPermissions() != null) {
permissions.addAll(account.getPermissions());
}
return roleHierarchy.getGrantedAuthorities(permissions)
.stream()
.map(GrantedAuthority.class::cast)
.collect(Collectors.toList());
}
}
还有一个:
public class WebAdminAuthoritiesExtractor implements AuthoritiesExtractor {
@Autowired
AccountRepository accountRepository;
@Autowired
RoleHierarchy roleHierarchy;
@Override
public List<GrantedAuthority> extractAuthorities(final Map<String, Object> map) {
val account = accountRepository.findByEmailIgnoreCase((String) map.get("email"));
final List<String> permissions = new ArrayList<>();
permissions.addAll(account.getPermissions());
return roleHierarchy.getGrantedAuthorities(permissions)
.stream()
.map(GrantedAuthority.class::cast)
.collect(Collectors.toList());
}
}
集成测试示例:
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
classes = WebAdminApplication.class,
value = { "management.port=-1",
"datasource.core.mongodb.port=0",
"datasource.ab-test.mongodb.port=0",
"security.oauth2.client.client-id=someid",
"security.oauth2.client.client-secret=some-secret"})
public class TestRest {
@Value("${local.server.port}")
private int httpServerPort;
@PostConstruct
public void postConstruct() {
RestAssured.port = httpServerPort;
}
@Before
public void setup() throws Exception {
}
@After
public void after() {
}
@Test
public void testCreateAssetConfig() {
System.out.println("\n\ntest one!\n\n");
}
}
结果: bootRun正常工作,WebSecurityConfig + OAuth2Configuration类正确触发,但对于集成测试,这些类甚至都没有触发。
错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpsEnforcingFilter': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'security.parameters.admin-enforce-ssl' in string value "${security.parameters.admin-enforce-ssl}"
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:372)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 31 more
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpsEnforcingFilter': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'security.parameters.admin-enforce-ssl' in string value "${security.parameters.admin-enforce-ssl}"
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:231)
at org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory.createDeploymentManager(UndertowEmbeddedServletContainerFactory.java:390)
at org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory.getEmbeddedServletContainer(UndertowEmbeddedServletContainerFactory.java:224)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:164)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134)
... 39 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpsEnforcingFilter': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'security.parameters.admin-enforce-ssl' in string value "${security.parameters.admin-enforce-ssl}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:234)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:182)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:177)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAdaptableBeans(ServletContextInitializerBeans.java:159)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:80)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getServletContextInitializerBeans(EmbeddedWebApplicationContext.java:241)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:228)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:89)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:213)
at org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory$Initializer.onStartup(UndertowEmbeddedServletContainerFactory.java:616)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:184)
... 43 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'security.parameters.admin-enforce-ssl' in string value "${security.parameters.admin-enforce-ssl}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:172)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:831)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1086)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
... 61 more
答案 0 :(得分:0)
您需要为测试类提供占位符值(security.parameters.admin-enforce-ssl,baseurl.admin以及您可能拥有的其他内容),因为列出@ SpringBootTest.value下的所有属性是痛苦的我建议你链接你的属性文件:
@SpringBootTest(properties={"locations=classpath:test.properties"})
确保所有必需的属性都在链接文件中。