Spring OAuth和Boot集成测试

Jak*_*och 4 spring-security spring-test spring-boot spring-security-oauth2

在OAuth资源服务器配置的Web应用程序中再次运行Spring Boot集成测试的最佳方法是什么.

我可以想到两种理论方法:

  1. 在没有实际调用授权服务器的情况下模拟资源服务器中的安全上下文.
  2. 将授权服务器作为测试的一部分嵌入,并将身份验证重定向到它.

我想知道其他人是如何解决这个问题的.

Rob*_*nch 12

这个答案与Ondrej提供的答案非常相似,但是相当简单.

Spring Security 4提供了测试支持.要使用它,请确保您具有spring-security-test-4.0.2.RELEASE.jar(或类路径上的更新版本).您还需要确保使用spring-test-4.1.0.RELEASE(或更新版本).

接下来,您可以使用MockMvc,如另一个答案所示.但是,如果您使用以下设置MockMvc:

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class OAuthTests {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)

                // ADD THIS!!
                .apply(springSecurity())
                .build();
    }
Run Code Online (Sandbox Code Playgroud)

这样就可以了

  • 您不再需要担心在无状态模式下运行
  • 这也意味着您不需要使用apply(springSecurity()),如另一个答案中所示.

简而言之,您应该能够做到这样的事情:

@Test
@WithSecurityContext('user')
public void performOAuth() throws Exception {
    ...    
    // No need for apply(security())!!
    restParcelMockMvc.perform(get("/api/some-resource"))
        .andExpect(...);
}
Run Code Online (Sandbox Code Playgroud)

我建议您阅读参考文献的其余Spring Security Testing部分,因为它提供了许多其他详细信息,包括如何使用自定义身份验证.


Ond*_*zek 4

我使用 spring security 4.x@WithSecurityContext('user')注释来创建登录模拟SecurityContext'user'然后,当使用我调用 REST API 时,MockMvc我检索SecurityContext并将其附加到调用中。

像这样:

@Test
@Transactional
@WithSecurityContext('user')
public void getAllParcels() throws Exception {
    // Initialize the database

    long size = parcelRepository.count();
    parcelRepository.saveAndFlush(parcel);

    // Get all the parcels
    restParcelMockMvc.perform(get("/api/parcels").with(security()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.[" + size + "].id").value(parcel.getId()))
        .andExpect(jsonPath("$.[" + size + "].lot").value(DEFAULT_LOT))
        .andExpect(jsonPath("$.[" + size + "].localName").value(DEFAULT_LOCAL_NAME));
}
Run Code Online (Sandbox Code Playgroud)

security()静态方法在哪里:

public static RequestPostProcessor security() {
        return SecurityMockMvcRequestPostProcessors.securityContext(SecurityContextHolder.getContext());
}
Run Code Online (Sandbox Code Playgroud)

因此,为我的测试方法创建了对经过身份验证的用户进行登录的@WithSecurityContext('user')模拟。然后,在该方法中,我检索此模拟并将其附加到 REST API 调用,以使我的 oAuth 认为用户已完成身份验证。这基本上是您在问题中建议的第一种方法。SecurityContext'user'SecurityContext

为此,您必须将 OAuth 切换为有状态才能进行测试。否则就行不通。

即像这样:

@Configuration
public class OAuth2ServerConfiguration {

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired(required = false)
        @Qualifier("oauth2StatelessSecurityContext")
        private Boolean stateless = Boolean.TRUE; // STATEFUL switching for tests!

        @Inject
        private Http401UnauthorizedEntryPoint authenticationEntryPoint;

        @Inject
        private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .logout()
                .logoutUrl("/api/logout")
                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameOptions().disable().and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/api/authenticate").permitAll()
                .antMatchers("/api/register").permitAll()
                .antMatchers("/api/logs/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api/**").authenticated()
                .antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/configprops/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/protected/**").authenticated();
        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.stateless(stateless);
            super.configure(resources);
        }

    }
...
Run Code Online (Sandbox Code Playgroud)

您会看到我的stateless属性仅在测试中注入。在正常运行中,它使用默认值true(因此它是无状态的)。对于测试,我声明oauth2StatelessSecurityContextBean 的值false,以便它在测试时变成有状态的。

我为测试定义了这个配置:

@Configuration
public class OAuth2Statefull {

    @Bean
    @Primary       
    public Boolean oauth2StatelessSecurityContext() {
        return Boolean.FALSE;
    }

}
Run Code Online (Sandbox Code Playgroud)

我就是这么做的。我希望我的解释是可以理解的。