Перенаправление с http на https в Spring Boot 2.0.4 - PullRequest
0 голосов
/ 24 декабря 2018

Я использую Spring boot 2.0.4.Я хочу настроить автоматическое перенаправление с http на https для всех шаблонов URL.Я добавляю в application.yml следующие строки:

server:
  ssl:
    enabled: true
    key-alias: tomcat
    key-store: "classpath:tomcat.keystore"
    key-store-type: jks
    key-store-password: 123456
    key-password: 123456

И я создал bean-компонент:

    @Bean
    public TomcatServletWebServerFactory httpsRedirectConfig() {
        return new TomcatServletWebServerFactory () {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
    }

Но, когда я запускаю свое приложение, у меня появляется ошибка:

Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans : tomcatServletWebServerFactory,httpsRedirectConfig

Что не так?Как я могу это исправить?Thx.

1 Ответ

0 голосов
/ 24 декабря 2018

Попробуйте использовать следующие конфигурации.

@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(redirectConnector());
    return tomcat;
}

private Connector redirectConnector() {
    Connector connector = new Connector(
            TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    connector.setScheme("http");
    connector.setPort(8080);
    connector.setSecure(false);
    connector.setRedirectPort(8443);
    return connector;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...