2
votes

Having troubles with integration test with Oauth2 and spring security... before adding Oauth2 config to the code base integration test worked correctly

Setup:

  • Client server with protected data also contains list of permissions, uses Spring Security and Oauth2
  • Authentication server which serves access tokens and doing authentication

Workflow:

  • when User trying to access resource from Client server without authentication system will redirect user to Authentication server login page
  • After authentication User redirected to the requested resource. Authentication server will send authentication to the Client server where Authentication object will be updated wth user permissions via (AuthoritiesExtractor, PrincipalExtractor).

Problem: I can start system and functionality works fine but now my integration test even could not start it complains that Can not create application context

Some configuration code:

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

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

Custom security logic:

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

And one more:

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

Integration test example:

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

Results: bootRun works and WebSecurityConfig + OAuth2Configuration classes triggered correctly but for integration tests those classes not even triggered.

Error:

    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
1
could you please look further down the stack trace, there should be listed an exact problem with loading your application contextborowis
added stack traceLugaru
so, Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'security.parameters.admin-enforce-ssl' in string value "${security.parameters.admin-enforce-ssl}" is the root cause, your test doesn't know where to look for variablesborowis
add a value in '@SpringBootTest' or link a property file with all the variables for the testborowis
did it, does not help still complains about application contextLugaru

1 Answers

0
votes

You will need to provide placeholder values for your test classes (security.parameters.admin-enforce-ssl, baseurl.admin and what else you might have), as listing all the properties under @SpringBootTest.value is painful I suggest you link your property files like this:

@SpringBootTest(properties={"locations=classpath:test.properties"})

And making sure all the required properties are inside linked files.