весенняя загрузка, автоматическое перенаправление http на https - PullRequest
0 голосов
/ 14 декабря 2018

Добрый день, у меня есть приложение с микросервисами и шлюзом (zuul), построенное на SpringBoot 2. Все это использует SSL.Мне нужно автоматическое перенаправление с: http: \\ localhost (в настоящее время ничего не показывает) на https: \\ localhost (показывает некоторый текст), поэтому пользователю не нужно беспокоиться.

Еще раз: http: \\ localhost должен показывать тот же текст, что и https: \\ localhost (мне нужен редирект)

Я пробовал, ничего не делает.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

Пробовал другой подход, но SpringBoot не смог распознать TomcatEmbeddedServletContainerFactory

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {

        @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(createHttpConnector());
    return tomcat;
}

private Connector createHttpConnector() {
    Connector connector
            = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setSecure(false);
    connector.setPort(8080);
    connector.setRedirectPort(8443);
    return connector;
}

этот тоже не работает (кажется, ничего не меняет)

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Environment environment;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // other security configuration missing

        http.portMapper()
                .http(80) // http port defined in yml config file
                .mapsTo(443); // https port defined in yml config file

        // we only need https on /auth
        http.requiresChannel()
                .antMatchers("/auth/**").requiresSecure()
                .anyRequest().requiresInsecure();
    }
}

и этот тоже не работает, ошибка Не удалось создать экземпляр [org.springframework.web.servlet.HandlerMapping]: фабричный метод 'resourceHandlerMapping' вызвал исключение;вложенное исключение - java.lang.IllegalStateException: не задано ServletContext

@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);
        }
    };
}

и даже это с java.lang.IllegalStateException: без заданного ServletContext ошибка

  @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(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        return connector;
    }

Есть предложения?

1 Ответ

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

Понял.Благодаря EstebanGarciaAlonso и его ответу ugrade spring boot 2.0.0.RC2 исключение Нет установленного ServletContext

"После отладкипроблема в том, что класс конфигурации mvc EnableWebMvcConfiguration загружен слишком рано, сервлет еще не загружен. "

Я потратил на это несколько часов.Мне удалось найти причину, почему это происходило.Моя конфигурация была разбита на несколько файлов, и я создавал bean-компонент, связанный с MVC, в Config Security (который был создан ранее), заставляя использовать конфигурацию MVC раньше времени.

Решением было перемещение экземпляра @Beanот конфигурации безопасности до конфигурации MVC.Я надеюсь, что это поможет другим людям!

Я переместил следующий код в Application.java как раз перед основным методом, и все работало как чудо

   @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(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        return connector;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...