当前位置: 首页 > 知识库问答 >
问题:

Spring Boot+集成测试+Oauth2

易昌翰
2023-03-14

与Oauth2和spring Security集成测试有问题...在将Oauth2配置添加到代码库之前,集成测试工作正常

设置:

  • 具有受保护数据的客户端服务器还包含权限列表,使用Spring Security和OAuth2
  • 提供访问令牌和执行身份验证的身份验证服务器

工作流:

    null
@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");
    }
}
    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个答案

冀越
2023-03-14

您将需要为您的测试类(security.parameters.admin-enforce-ssl、baseurl.admin和您可能拥有的其他内容)提供占位符值,因为在@springboottest.value下列出所有属性是很痛苦的。我建议您如下所示链接您的属性文件:

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

并确保所有必需的属性都在链接文件中。

 类似资料:
  • 我正在使用一个带有spring boot 2.0.0.rc1的多项目分级器。我的子项目之一是SpringBoot应用程序,其中包含了我的集成测试。 集成测试用WebEnvironment.random_port标记为@springboottest。由于未解析的依赖关系(在另一个子项目中声明的服务,的同级),测试失败,使用了gradle命令行,但在Eclipse IDE中成功。 如果有人有主意?如何

  • 我有几个繁重的Spring集成测试(是的,这不是最好的方法,我没有时间正确地模拟所有外部dep) 下面是测试的典型注释 由于以下原因,测试会定期失败: 这里有两个问题:1、让测试共存的正确方式是什么?我在surefire插件中设置了forkCount=0。好像有帮助 2.1. 在每次测试期间,我实际上不需要启动所有的

  • 与@mockbean和@spybean一样,有没有类似于@fakebean/@dummybean的东西? 其思想是,该实例是100%真实的(具有预期的生产内部状态),并且它覆盖(或者添加bean,以防在配置中没有声明)上下文中的bean。理想情况下,您不需要创建TestConfiguration类并将其设置为Primary,因为这样可以在每个测试的基础上控制假冒,只有在需要时才可以。否则它使用主的

  • 英文原文:http://emberjs.com/guides/testing/integration/ 集成测试通常用来测试应用中得重要工作流。集成测试用来模拟用户交互和确认交互结果。 设置 为了对Ember应用进行集成测试,需要在测试框架中运行应用。首先需要将根元素(root element)设置为任意一个已知将存在的元素。如果根元素在测试运行时可见的话,这对测试驱动开发非常有用,带来的帮助非常

  • 已删除MyTestConfig.class,但问题仍然相同。即使我使用@SpringBootTest(classes={Application.Class,MyProblematicServiceImpl.Class}),它仍然在自动连线的地方返回模拟对象。MyProblematicServiceImpl是用@Service注释的空类。

  • 主要内容:集成测试背后的原因,集成测试技术,集成测试方法,集成测试指南集成测试是单元测试后软件测试过程的第二个层次。在此测试中,软件的单元或单个组件在组中进行测试。集成测试级别的重点是在集成组件或单元之间交互时暴露缺陷。 单元测试使用模块进行测试,这些模块在集成测试中进行组合和测试。该软件使用许多软件模块开发,这些软件模块由不同的编码器或程序员编码。集成测试的目标是检查所有模块之间通信的正确性。 集成测试背后的原因 虽然软件应用程序的所有模块已经在单元测试中进行了测

  • 设计 集成测试包括 3 个模块:测试用例、测试环境以及测试引擎。 测试用例 用于定义待测试的 SQL 以及测试结果的断言数据。 每个用例定义一条 SQL,SQL 可定义多种数据库执行类型。 测试环境 用于搭建运行测试用例的数据库和 ShardingSphere-Proxy 环境。 环境又具体分为环境准备方式,数据库类型和场景。 环境准备方式分为 Native 和 Docker,未来还将增加 Emb