Home > Mobile >  Spring-boot redirect:/ to http instead of https
Spring-boot redirect:/ to http instead of https

Time:10-29

When redirecting to a relative path in spring-boot controller like below code. It is always redirecting to http url when the application is deployed in https environment. So I am getting mixed origin content blocked error in browser.

return "redirect:/redirectUrl";

The application is deployed in weblogic server.

CodePudding user response:

First, open the application.properties file and add server.http.port property to define a port for HTTP, and server.port property for HTTPS.

Note: server.http.port is a property you define and not available in SpringBoot.

In application.properties file:

    # (User-defined Property)
    # Port for HTTP and read by Spring Boot via @Value("${server.http.port:80}")
    server.http.port=8080
    
    # Port for HTTPS and read by Spring Boot via @Value("${server.port:443}")
    server:
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: pkcs12
    key-alias: springboot
    key-password: password
  port: 8443
  • server.port: the port on which the server is listening. We have used 8443 rather than the default 8080 port.
  • server.ssl.key-store: the path to the key store that contains the SSL certificate. In our example, we want Spring Boot to look for it in the classpath.
  • server.ssl.key-store-password: the password used to access the key store.
  • server.ssl.key-store-type: the type of the key store (JKS or PKCS12).
  • server.ssl.key-alias: the alias that identifies the key in the key store.
  • server.ssl.key-password: the password used to access the key in the key store.

Next, create a HttpHttpsConfig class and configure Spring Boot to use both HTTP and HTTPS protocols at the same time.

@Configuration
public class HttpHttpsConfig {

    // (User-defined Property)
    @Value("${server.http.port:80}")
    private int httpPort;

    @Bean
    public ServletWebServerFactory servletContainer() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setPort(this.httpPort);

        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}

If that doesn't work for you you can consider the references for different strategies and implementation.

reference-1

reference-2

CodePudding user response:

Try adding the following to your WEB-INF/web.xml file...

<web-app>
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>SecureResources</web-resource-name>
      <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
</web-app>

That should cause any http requests to be redirected to https.

  • Related