【问题标题】:Spring integration test, prevent redirect to be able to compare status codeSpring集成测试,防止重定向能够比较状态码
【发布时间】:2016-03-03 23:53:50
【问题描述】:

我正在尝试对我的 Spring-boot 应用程序进行集成测试。我有一个受保护的端点(/uaa/change_password,Spring MVC),它在未通过身份验证时重定向到 /uaa/login。如何拦截我发送的请求,我只为 /uaa/login 页面返回 200 OK。所以 assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); 的测试失败了,因为状态码是 200。(另一个测试也失败了)。任何帮助表示赞赏。

代码:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApiAuthServerApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class ApiAuthServerApplicationTests {

    @Value("${local.server.port}")
    private int port;

    private RestTemplate template = new TestRestTemplate();

    @Test
    public void changePasswordPageProtected() {
        ResponseEntity<String> response = template.getForEntity("http://localhost:"
                + port + "/uaa/change_password", String.class);

        assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
        String auth = response.getHeaders().getFirst("WWW-Authenticate");
        assertTrue("Wrong header: " + auth, auth.startsWith("Bearer realm"));
    }
}

我的配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {          
        http
            .formLogin().loginPage("/login").permitAll()
        .and()
            .requestMatchers().antMatchers(                     
                    "/login", 
                    "/oauth/authorize",                     
                    "/oauth/confirm_access", 
                    "/reset_password", 
                    "/forgot_password",
                    "/change_password")     
        .and()
            .authorizeRequests()
            .antMatchers("/reset_password", "/forgot_password").permitAll()             
            .anyRequest().authenticated();
    }

【问题讨论】:

    标签: spring spring-mvc spring-boot spring-test


    【解决方案1】:

    您需要在RestTemplate 中禁用自动重定向。为此,我推荐Apache HTTP Client

    您将在下面找到如何配置RestTemplate 以不关注HTTP 302 的示例:

    import org.apache.http.client.HttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
    
    ....
    
    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
    new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    

    【讨论】:

    • 实际上我只需要将 testCompile('org.apache.httpcomponents:httpclient:4.5.1') 添加到我的 gradle 构建中,因此它可以在类路径中使用。感谢@ksokol 的指导。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2013-04-26
    • 2021-10-15
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多