SpringBoot Undertow将POST从HTTP重定向到HTTPS

时间:2016-05-26 14:47:46

标签: redirect spring-boot undertow

我已经在StackOverflow上阅读了这些帖子:

Redirect http to https on spring boot embedded undertow

Spring RestTemplate redirect 302

Redirect HTTP to HTTPS in Undertow

我想将Undertow配置为使用GET和POST从HTTP重定向到HTTPS。 GET有效,但是在POST时,它会查找具有相同URL的GET方法(在我的情况下,它会找到)。

我的服务器配置:

@Configuration
public class UndertowConfig {

    @Bean
    public EmbeddedServletContainerFactory undertow() {
        UndertowEmbeddedServletContainerFactory undertow = new   UndertowEmbeddedServletContainerFactory();
        undertow.addBuilderCustomizers(builder -> builder.addHttpListener(8080, "0.0.0.0"));
        undertow.addDeploymentInfoCustomizers(deploymentInfo -> {
            deploymentInfo.addSecurityConstraint(new SecurityConstraint()
            .addWebResourceCollection(new WebResourceCollection()
            .addUrlPattern("/*"))
            .setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
            .setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT))
                .setConfidentialPortManager(exchange -> 8443);
        });
        return undertow;
    }
}

强制HTTPS:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requiresChannel().anyRequest().requiresSecure();
    }
}

控制器:

@RestController
public class HelloController {

    @RequestMapping("/")
    public String get() {
        return "GET";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String post() {
        return "POST";
    }

}

客户端:

public class Client {

    public static void main(String[] args) {

        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).setSSLHostnameVerifier((hostname, session) -> true).build();
        factory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(factory);
        String get = restTemplate.getForObject("http://localhost:8080/", String.class);
        ResponseEntity<String> post = restTemplate.postForEntity("http://localhost:8080/", null, String.class);
}

}

如何让POST请求进入POST?

0 个答案:

没有答案