Spring Boot启用HTTPS

启用HTTPS

server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=secret
server.ssl.key-password=another-secret

management server可以使用不同的端口,不使用HTTPS:

server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:store.jks
server.ssl.key-password=secret
management.server.port=8080
management.server.ssl.enabled=false

management server也可以使用不同的key store:

server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:main.jks
server.ssl.key-password=secret
management.server.port=8080
management.server.ssl.enabled=true
management.server.ssl.key-store=classpath:management.jks
management.server.ssl.key-password=secret

通过配置application.properties不支持同时启用HTTP和HTTPS,如要两者同时启用,推荐在配置文件中配置HTTPS,在程序中增加HTTP支持:

import org.apache.catalina.connector.Connector;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;

/**
 * Sample Application to show Tomcat running two connectors.
 *
 * @author Brock Mills
 * @author Andy Wilkinson
 */
@SpringBootApplication
public class SampleTomcatTwoConnectorsApplication {

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }

    private Connector createStandardConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(0);
        return connector;
    }

    public static void main(String[] args) {
        SpringApplication.run(SampleTomcatTwoConnectorsApplication.class, args);
    }

}

使用keytool生成证书:

keytool -genkeypair -alias itrunner -keyalg RSA -dname "cn=www.itrunner.org, ou=itrunner, o=itrunner, c=CN" -validity 365 -keystore keystore.jks -storepass secret -storetype pkcs12

调用HTTPS REST服务

在调用HTTPS REST服务时需要配置受信证书,可使用keytool导入证书,生成trust-store文件:

keytool -import -alias "my server cert" -file server.crt -keystore my.truststore

Java默认受信证书存储在${JAVA_HOME}/jre/lib/security/cacerts内,初始密码为"changeit",可使用keytool查看:

keytool -list -keystore cacerts -v

也可自定义信任策略(TrustStrategy),忽略标准的信任验证流程。下面分别示例使用Spring RestTemplate和JAX-RS调用HTTPS REST服务,忽略验证证书和Hostname。

RestTemplate

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.cert.X509Certificate;

public class HttpsRest {
    public static void main(String[] args) throws Exception {
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true).build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);

        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.postForObject(url, request, responseType);
    }
}

JAX-RS

如使用Jboss服务器,配置如下依赖:

<dependency>
  <groupId>org.jboss.spec.javax.ws.rs</groupId>
  <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
  <version>1.0.2.Final</version>
  <scope>provided</scope>
</dependency>

示例代码:

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import java.security.cert.X509Certificate;

public class HttpsRest {
    public static void main(String[] args) throws Exception {
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true).build();
        Client client = ClientBuilder.newBuilder().hostnameVerifier(NoopHostnameVerifier.INSTANCE).sslContext(sslContext).build();
        Entity<User> requestEntity = Entity.entity(new User(), MediaType.APPLICATION_JSON_TYPE);
        client.target(url).request().post(requestEntity, responseType);
        client.close();
    }
}

参考文档

Spring Boot Reference Guide
spring-boot-sample-tomcat-multi-connectors

原文地址:http://blog.51cto.com/7308310/2333550

时间: 2024-10-09 09:24:11

Spring Boot启用HTTPS的相关文章

Spring Boot启用Swagger2

Swagger2是一个开源项目,用于为RESTful Web服务生成REST API文档. 它提供了一个用户界面,可通过Web浏览器访问RESTful Web服务. 要在Spring Boot应用程序中启用Swagger2,需要在构建配置文件中添加以下依赖项. <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <v

Spring Boot 启用Gzip压缩

有两点需要注意 1.需要在application.properties里启用压缩,并设置压缩支持的格式(默认支持text/html等,但不支持application/json) server.compression.enabled=true server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain 2.默认情况下,仅会压缩2048字节以上的内容 #默认就是2048 by

Spring Boot SSL [https]配置例子

前言 本文主要介绍Spring Boot HTTPS相关配置,基于自签证书实现: 通过本例子,同样可以了解创建SSL数字证书的过程: 本文概述 Spring boot HTTPS 配置 server.port=8443 server.ssl.key-alias=selfsigned_localhost_sslserver server.ssl.key-password=changeit server.ssl.key-store=classpath:ssl-server.jks server.ss

Spring boot 配置https 实现java通过https接口访问

近来公司需要搭建一个https的服务器来调试接口(服务器用的spring boot框架),刚开始接触就是一顿百度,最后发现互联网认可的https安全链接的证书需要去CA认证机构申请,由于是调试阶段就采用了java的keytool工具来生成密钥文件,下面是生成密钥文件的指令和步骤(前提是需要配置好java 的环境变量). 1.首先打开cmd命令,操作如下: keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 20

IDEA 中 Spring Boot 启用热部署

maven 配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/

spring boot 启用 actuator

<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId>

spring boot 与 vue 配置 https

一.系统环境 win10 二.spring boot 配置 https 1.keytool生成证书 打开cmd,使用keytool生成证书,keytool是jdk中的一个证书管理工具,可以生成自签名证书 keytool -genkey -alias tomcat -keyalg RSA -keystore server.keystore 生成了对应的文件,如下: 2.参数配置 将证书copy至项目中 配置application.yml server: port: 8324 http: port:

Spring Boot, Java Config - No mapping found for HTTP request with URI [/…] in DispatcherServlet with name &#39;dispatcherServlet&#39;

Spring Boot 启用应用: error: No mapping found for HTTP request with URI [/…] in DispatcherServlet with name 'dispatcherServlet' solution: @SpringBootApplication(scanBasePackages={"micro.service.basic", Spring Boot, Java Config - No mapping found for

剑指架构师系列-spring boot的logback日志记录

Spring Boot集成了Logback日志系统. Logback的核心对象主要有3个:Logger.Appender.Layout 1.Logback Logger:日志的记录器 主要用于存放日志对象,也可以定义日志类型.级别. 级别:ERROR.WARE.INFO.DEBUG和TRACE.没有FATAL,归纳到了ERROR级别里.ERROR.WARN and INFO level messages are logged by default. 在Spring Boot中,最好定义为logb