Spring Загрузка перенаправления HTTP на HTTPS
Для Spring загрузочного приложения у меня есть конфигурационные свойства ssl в application.properties, см. мою конфигурацию здесь:
server.port=8443
server.ssl.key-alias=tomcat
server.ssl.key-password=123456
server.ssl.key-store=classpath:key.p12
server.ssl.key-store-provider=SunJSSE
server.ssl.key-store-type=pkcs12
И я добавил связь в Application.class, например
@Bean
public EmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
final TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.addAdditionalTomcatConnectors(this.createConnection());
return factory;
}
private Connector createConnection() {
final String protocol = "org.apache.coyote.http11.Http11NioProtocol";
final Connector connector = new Connector(protocol);
connector.setScheme("http");
connector.setPort(9090);
connector.setRedirectPort(8443);
return connector;
}
Но когда я попробую следующее
http://127.0.0.1:9090/
перенаправить на
https://127.0.0.1:8443/
не выполняется. Кто столкнулся с подобной проблемой?
Ответы
Ответ 1
Чтобы Tomcat выполнял перенаправление, вам необходимо настроить его с одним или несколькими ограничениями безопасности. Вы можете сделать это, выполнив постобработку Context
с помощью подкласса TomcatEmbeddedServletContainerFactory
.
Например:
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);
}
};
Благодаря CONFIDENTIAL
и /*
, это заставит Tomcat перенаправить каждый запрос на HTTPS. Вы можете настроить несколько шаблонов и несколько ограничений, если вам нужно больше контролировать то, что есть и не перенаправлено.
Ответ 2
Установка этого свойства в файл приложения *.properties(и соответствующая конфигурация сервлета для заголовков HTTPS в случае, если вы работаете за прокси-сервером) и Spring Настройка безопасности (например, с org.springframework.boot: spring -boot-starter-security на вашем пути к классам) должно быть достаточно:
security.require-ssl=true
Теперь по какой-то причине эта конфигурация не выполняется, когда базовая проверка подлинности отключена (по крайней мере, в старых версиях Spring Boot). Поэтому в этом случае вам нужно будет сделать дополнительный шаг и почитать его самостоятельно, вручную настроив безопасность на свой код, например:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject private SecurityProperties securityProperties;
@Override
protected void configure(HttpSecurity http) throws Exception {
if (securityProperties.isRequireSsl()) http.requiresChannel().anyRequest().requiresSecure();
}
}
Итак, если вы используете Tomcat за прокси-сервером, у вас будут все эти свойства в вашем приложении *.properties file:
security.require-ssl=true
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
Ответ 3
Утвержденный ответ мне не хватило.
Мне также пришлось добавить следующее в мою конфигурацию веб-безопасности, поскольку я не использую порт 8080 по умолчанию:
@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(Integer.parseInt(environment.getProperty("server.http.port"))) // http port defined in yml config file
.mapsTo(Integer.parseInt(environment.getProperty("server.port"))); // https port defined in yml config file
// we only need https on /auth
http.requiresChannel()
.antMatchers("/auth/**").requiresSecure()
.anyRequest().requiresInsecure();
}
}
Ответ 4
Выполняйте только два шага.
1- Добавить spring зависимость безопасности в pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2- Добавьте этот класс в корневой пакет вашего приложения.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().anyRequest().requiresSecure();
}
}
Ответ 5
В Spring-Boot нужна зависимость ниже
Шаг 1-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Шаг 2- Просто нужно сделать следующие настройки в файле application.properties
- server.port=8443
- server.ssl.key.alias=ode-https
- server.ssl.key-store-type=JKS (just for testing i USED JSK, but for production normally use pkcs12)
- server.ssl.key-password=password
- server.ssl.key-store=classpath:ode-https.jks
Шаг 3- теперь необходимо сгенерировать сертификат, используя вышеуказанные детали.
keytool -genkey -alias ode-https -storetype JKS -keyalg RSA -keys из 2048 -validity 365 -keys разорвал ode-https.jks
Шаг 4- переместите сертификат в папку ресурсов в вашей программе.
Шаг 5- Создать конфигурационный класс
@Configuration
public class HttpsConfiguration {
@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;
}
@Value("${server.port.http}") //Defined in application.properties file
int httpPort;
@Value("${server.port}") //Defined in application.properties file
int httpsPort;
private Connector redirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(httpPort);
connector.setSecure(false);
connector.setRedirectPort(httpsPort);
return connector;
}
}
это.
Ответ 6
Для Jetty (тестируется с 9.2.14) вам нужно добавить дополнительную конфигурацию в WebAppContext
(настройте pathSpec
на свой вкус):
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.webapp.AbstractConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
class HttpToHttpsJettyConfiguration extends AbstractConfiguration
{
// http://wiki.eclipse.org/Jetty/Howto/Configure_SSL#Redirecting_http_requests_to_https
@Override
public void configure(WebAppContext context) throws Exception
{
Constraint constraint = new Constraint();
constraint.setDataConstraint(2);
ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setPathSpec("/*");
constraintMapping.setConstraint(constraint);
ConstraintSecurityHandler constraintSecurityHandler = new ConstraintSecurityHandler();
constraintSecurityHandler.addConstraintMapping(constraintMapping);
context.setSecurityHandler(constraintSecurityHandler);
}
}
Затем подключите этот класс, добавив @Configuration
класс, реализующий EmbeddedServletContainerCustomizer
вместе с новым Connector
, который прослушивает небезопасный порт:
@Configuration
public class HttpToHttpsJettyCustomizer implements EmbeddedServletContainerCustomizer
{
@Override
public void customize(ConfigurableEmbeddedServletContainer container)
{
JettyEmbeddedServletContainerFactory containerFactory = (JettyEmbeddedServletContainerFactory) container;
//Add a plain HTTP connector and a WebAppContext config to force redirect from http->https
containerFactory.addConfigurations(new HttpToHttpsJettyConfiguration());
containerFactory.addServerCustomizers(server -> {
HttpConfiguration http = new HttpConfiguration();
http.setSecurePort(443);
http.setSecureScheme("https");
ServerConnector connector = new ServerConnector(server);
connector.addConnectionFactory(new HttpConnectionFactory(http));
connector.setPort(80);
server.addConnector(connector);
});
}
}
Это означает, что SSL Connector
уже настроен и прослушивается на порту 443 в этом примере.
Ответ 7
Поскольку TomcatEmbeddedServletContainerFactory
был удален в Spring Boot 2, используйте это:
@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);
}
};
}
Ответ 8
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().anyRequest().requiresSecure();
}
}
Чтобы избежать бесконечного цикла перенаправления (есть на gcloud)
добавьте эти строки в свойства приложения:
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
Ответ 9
Для Spring Boot 2 я настроил свой сервер ресурсов со следующей @Configuration
:
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requiresChannel()
/* Require HTTPS evereywhere*/
.antMatchers("/**")
.requiresSecure();
}
}
И это в основном это