我正在使用 springBootVersion 1.2.0.RELEASE 。
我试图通过application.properties
配置我的密钥库和信任库。
当我添加以下设置时,我可以让密钥库工作,但不能使用信任库。
server.ssl.key-store=classpath:foo.jks
server.ssl.key-store-password=password
server.ssl.key-password=password
server.ssl.trust-store=classpath:foo.jks
server.ssl.trust-store-password=password
但是,如果我通过gradle添加信任库:
bootRun {
jvmArgs = [ "-Djavax.net.ssl.trustStore=c://foo.jks", "-Djavax.net.ssl.trustStorePassword=password"]
}
它运作得很好。
是否有人将application.properties
用于信任商店?
答案 0 :(得分:26)
如果您需要进行REST呼叫,可以使用下一种方式。
这适用于RestTemplate
的拨出电话。
像这样声明RestTemplate
bean。
@Configuration
public class SslConfiguration {
@Value("${http.client.ssl.trust-store}")
private Resource keyStore;
@Value("${http.client.ssl.trust-store-password}")
private String keyStorePassword;
@Bean
RestTemplate restTemplate() throws Exception {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(
keyStore.getURL(),
keyStorePassword.toCharArray()
).build();
SSLConnectionSocketFactory socketFactory =
new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory =
new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(factory);
}
}
http.client.ssl.trust-store
和http.client.ssl.trust-store-password
指向JKS
格式的信任库以及指定信任库的密码。
这将覆盖Spring Boot提供的RestTemplate
bean,并使其使用您需要的信任存储。
答案 1 :(得分:12)
我有同样的问题,我会尝试更详细地解释一下。
我正在使用spring-boot 1.2.2-RELEASE并在Tomcat和Undertow上尝试使用相同的结果。
在application.yml中定义信任存储,如:
server:
ssl:
trust-store: path-to-truststore...
trust-store-password: my-secret-password...
不起作用,而:
$ java -Djavax.net.debug=ssl -Djavax.net.ssl.trustStore=path-to-truststore... -Djavax.net.ssl.trustStorePassword=my-secret-password... -jar build/libs/*.jar
完美无缺。
在rutime中查看差异的最简单方法是在客户端启用ssl-debug。工作时(即使用-D标志)将类似以下内容的内容写入控制台(在处理第一个请求期间):
trustStore is: path-to-truststore...
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert:
Subject: C=..., ST=..., O=..., OU=..., CN=...
Issuer: C=..., ST=..., O=..., OU=..., CN=...
Algorithm: RSA; Serial number: 0x4d2
Valid from Wed Oct 16 17:58:35 CEST 2013 until Tue Oct 11 17:58:35 CEST 2033
没有-D标志我得到:
trustStore is: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/security/cacerts
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert: ... (one for each CA-cert in the defult truststore)
...当执行请求时,我得到了异常:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
希望能更好地理解这个问题!
答案 2 :(得分:11)
我在Spring Boot,Spring Cloud(微服务)和自签名SSL证书方面遇到了同样的问题。 Keystore从应用程序属性开箱即用,而Truststore没有。
我最终在application.properties中保留了keystore和trustore配置,并添加了一个单独的配置bean,用于使用System配置信任库属性。
@Configuration
public class SSLConfig {
@Autowired
private Environment env;
@PostConstruct
private void configureSSL() {
//set to TLSv1.1 or TLSv1.2
System.setProperty("https.protocols", "TLSv1.1");
//load the 'javax.net.ssl.trustStore' and
//'javax.net.ssl.trustStorePassword' from application.properties
System.setProperty("javax.net.ssl.trustStore", env.getProperty("server.ssl.trust-store"));
System.setProperty("javax.net.ssl.trustStorePassword",env.getProperty("server.ssl.trust-store-password"));
}
}
答案 3 :(得分:7)
我也遇到了与Spring Boot和嵌入式Tomcat相同的问题。
根据我的理解,这些属性仅设置Tomcat配置参数。根据Tomcat文档,这仅用于客户端身份验证(即双向SSL),而不用于验证远程证书:
truststoreFile - 用于验证客户端证书的信任库文件。
https://tomcat.apache.org/tomcat-8.0-doc/config/http.html
为了配置HttpClient的信任库,它在很大程度上取决于您使用的HttpClient实现。例如,对于RestTemplate,Spring Boot默认使用基于标准J2SE类的SimpleClientHttpRequestFactory,如java.net.HttpURLConnection。
我已经提出了基于Apache HttpClient文档和这些帖子的解决方案: http://vincentdevillers.blogspot.pt/2013/02/configure-best-spring-resttemplate.html http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
基本上,这允许RestTemplate bean仅信任由配置的信任库中的根CA签名的证书。
@Configuration
public class RestClientConfig {
// e.g. Add http.client.ssl.trust-store=classpath:ssl/truststore.jks to application.properties
@Value("${http.client.ssl.trust-store}")
private Resource trustStore;
@Value("${http.client.ssl.trust-store-password}")
private char[] trustStorePassword;
@Value("${http.client.maxPoolSize}")
private Integer maxPoolSize;
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public HttpClient httpClient() {
// Trust own CA and all child certs
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
try {
SSLContext sslContext = SSLContexts
.custom()
.loadTrustMaterial(trustStore.getFile(),
trustStorePassword)
.build();
// Since only our own certs are trusted, hostname verification is probably safe to bypass
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
new HostnameVerifier() {
@Override
public boolean verify(final String hostname,
final SSLSession session) {
return true;
}
});
socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
} catch (Exception e) {
//TODO: handle exceptions
e.printStackTrace();
}
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(maxPoolSize);
// This client is for internal connections so only one route is expected
connectionManager.setDefaultMaxPerRoute(maxPoolSize);
return HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.disableCookieManagement()
.disableAuthCaching()
.build();
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(httpRequestFactory());
return restTemplate;
}
}
然后您可以在需要时使用此自定义Rest客户端,例如:
@Autowired
private RestTemplate restTemplate;
restTemplate.getForEntity(...)
这假设您尝试连接到Rest端点,但您也可以使用上述HttpClient bean进行任何操作。
答案 4 :(得分:4)
java properties&#34; javax.net.ssl.trustStore&#34;和&#34; javax.net.ssl.trustStorePassword&#34;不对应&#34; server.ssl.trust-store&#34;和&#34; server.ssl.trust-store-password&#34;来自Spring boot&#34; application.properties&#34; (&#34; application.yml&#34)
所以你不能设置&#34; javax.net.ssl.trustStore&#34;和&#34; javax.net.ssl.trustStorePassword&#34;只需设置&#34; server.ssl.trust-store&#34;和&#34; server.ssl.trust-store-password&#34; in&#34; application.properties&#34; (&#34; application.yml&#34)
另一种设置&#34; javax.net.ssl.trustStore&#34;和&#34; javax.net.ssl.trustStorePassword&#34;是由春季启动Externalized Configuration
以下是我的实施摘录:
Params类保存外部设置
@Component
@ConfigurationProperties("params")
public class Params{
//default values, can be override by external settings
public static String trustStorePath = "config/client-truststore.jks";
public static String trustStorePassword = "wso2carbon";
public static String keyStorePath = "config/wso2carbon.jks";
public static String keyStorePassword = "wso2carbon";
public static String defaultType = "JKS";
public void setTrustStorePath(String trustStorePath){
Params.trustStorePath = trustStorePath;
}
public void settrustStorePassword(String trustStorePassword){
Params.trustStorePassword=trustStorePassword;
}
public void setKeyStorePath(String keyStorePath){
Params.keyStorePath = keyStorePath;
}
public void setkeyStorePassword(String keyStorePassword){
Params.keyStorePassword = keyStorePassword;
}
public void setDefaultType(String defaultType){
Params.defaultType = defaultType;
}
KeyStoreUtil类承担&#34; javax.net.ssl.trustStore&#34;的设置。和&#34; javax.net.ssl.trustStorePassword&#34;
public class KeyStoreUtil {
public static void setTrustStoreParams() {
File filePath = new File( Params.trustStorePath);
String tsp = filePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", tsp);
System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);
}
public static void setKeyStoreParams() {
File filePath = new File(Params.keyStorePath);
String ksp = filePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", ksp);
System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);
}
}
你得到在启动函数中执行的setter
@SpringBootApplication
@ComponentScan("com.myapp.profiles")
public class ProfilesApplication {
public static void main(String[] args) {
KeyStoreUtil.setKeyStoreParams();
KeyStoreUtil.setTrustStoreParams();
SpringApplication.run(ProfilesApplication.class, args);
}
}
于2018-10-03编辑
您可能还想采用注释&#34; PostConstruct&#34;作为执行setter的替代方法
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages={"com.xxx"})
public class GateApplication {
public static void main(String[] args) {
SpringApplication.run(GateApplication.class, args);
}
@PostConstruct
void postConstruct(){
setTrustStoreParams();
setKeyStoreParams();
}
private static void setTrustStoreParams() {
File filePath = new File( Params.trustStorePath);
String tsp = filePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", tsp);
System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);
}
private static void setKeyStoreParams() {
File filePath = new File(Params.keyStorePath);
String ksp = filePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", ksp);
System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);
}
}
application.yml
---
params:
trustStorePath: config/client-truststore.jks
trustStorePassword: wso2carbon
keyStorePath: config/wso2carbon.jks
keyStorePassword: wso2carbon
defaultType: JKS
---
最后,在运行环境(部署服务器)中,创建一个名为&#34; config&#34;的文件夹。在存储jar存档的同一文件夹下。
在&#34; config&#34;文件夹,存储&#34; application.yml&#34;,&#34; client-truststore.jks&#34;,&#34; wso2carbon.jks&#34;。完成了!
关于Spring boot 2.x.x的更新2018-11-27
从spring boot 2.x.x开始,不再支持静态属性,请see here。我个人认为这不是一个好的举动,因为必须在参考链上进行复杂的改变......
无论如何,一个推理摘录可能看起来像这样
&#39> Params&#39;班级 import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* Params class represent all config parameters that can
* be external set by spring xml file
*/
@Component
@ConfigurationProperties("params")
@Data
public class Params{
//default values, can be override by external settings
public String trustStorePath = "config/client-truststore.jks";
public String trustStorePassword = "wso2carbon";
public String keyStorePath = "config/wso2carbon.jks";
public String keyStorePassword = "wso2carbon";
public String defaultType = "JKS";
}
Springboot应用程序类&#39; (使用&#39; PostConstruct&#39;)
import java.io.File;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages={"com.xx.xx"})
public class BillingApplication {
@Autowired
Params params;
public static void main(String[] args) {
SpringApplication.run(BillingApplication.class, args);
}
@PostConstruct
void postConstruct() {
// set TrustStoreParams
File trustStoreFilePath = new File(params.trustStorePath);
String tsp = trustStoreFilePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", tsp);
System.setProperty("javax.net.ssl.trustStorePassword", params.trustStorePassword);
System.setProperty("javax.net.ssl.keyStoreType", params.defaultType);
// set KeyStoreParams
File keyStoreFilePath = new File(params.keyStorePath);
String ksp = keyStoreFilePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", ksp);
System.setProperty("Security.KeyStore.Password", params.keyStorePassword);
}
}
答案 5 :(得分:2)
这是我Oleksandr Shpota's answer的扩展版本,包括导入。可以在org.apache.httpcomponents:httpclient
中找到包org.apache.http.*
。我评论了这些变化:
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Value("${http.client.ssl.key-store}")
private Resource keyStore;
@Value("${http.client.ssl.trust-store}")
private Resource trustStore;
// I use the same pw for both keystores:
@Value("${http.client.ssl.trust-store-password}")
private String keyStorePassword;
// wasn't able to provide this as a @Bean...:
private RestTemplate getRestTemplate() {
try {
SSLContext sslContext = SSLContexts.custom()
// keystore wasn't within the question's scope, yet it might be handy:
.loadKeyMaterial(
keyStore.getFile(),
keyStorePassword.toCharArray(),
keyStorePassword.toCharArray())
.loadTrustMaterial(
trustStore.getURL(),
keyStorePassword.toCharArray(),
// use this for self-signed certificates only:
new TrustSelfSignedStrategy())
.build();
HttpClient httpClient = HttpClients.custom()
// use NoopHostnameVerifier with caution, see https://stackoverflow.com/a/22901289/3890673
.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()))
.build();
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
} catch (IOException | GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
答案 6 :(得分:1)
如果您将Spring Boot应用程序作为Linux服务(例如init.d脚本或类似程序)执行,那么您还有以下选项: 创建一个名为yourApplication.conf的文件,并将其放在可执行的war / jar文件旁边。它的内容应该类似:
JAVA_OPTS="
-Djavax.net.ssl.trustStore=path-to-your-trustStore-file
-Djavax.net.ssl.trustStorePassword=yourCrazyPassword
"
答案 7 :(得分:0)
如果您使用的是Spring,请尝试为其添加属性(使用所需的属性),它应该适用于整个JVM
javax:
net:
ssl:
key-store-password: ${KEYSTORE_SECRET}
key-store-type: PKCS12
trust-store-password: ${TRUSTSTORE_SECRET}
trust-store-type: PKCS12
答案 8 :(得分:0)
尽管我评论迟了。但是我已经使用这种方法来完成这项工作。在这里,当我运行spring应用程序时,我将通过-Dspring.config.location=file:/location-to-file/config-server-vault-application.yml
提供应用程序yaml文件,其中包含我的所有属性
config-server-vault-application.yml
***********************************
server:
port: 8888
ssl:
trust-store: /trust-store/config-server-trust-store.jks
trust-store-password: config-server
trust-store-type: pkcs12
************************************
Java Code
************************************
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) throws IOException {
setUpTrustStoreForApplication();
SpringApplication.run(ConfigServerApplication.class, args);
}
private static void setUpTrustStoreForApplication() throws IOException {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
List<PropertySource<?>> applicationYamlPropertySource = loader.load(
"config-application-properties", new UrlResource(System.getProperty("spring.config.location")));
Map<String, Object> source = ((MapPropertySource) applicationYamlPropertySource.get(0)).getSource();
System.setProperty("javax.net.ssl.trustStore", source.get("server.ssl.trust-store").toString());
System.setProperty("javax.net.ssl.trustStorePassword", source.get("server.ssl.trust-store-password").toString());
}
}
答案 9 :(得分:0)
当一切听起来如此复杂时,此命令对我有用:
const rpProxy = {
apply: (target, thisArg, argumentsList) => {
return requestPromiseWithRetry(target(argumentsList[0]));
}
}
export const requestPromiseWithRetry = (promise: Promise<any>, retryOptions?): Promise<any> => {
var options = {retries: 2, minTimeout: 300}
return promiseRetry(options, function (retry, number) {
return promise
.catch((err) => {
if(err.message && err.message.indexOf("socket hang up")>-1){
console.log(err);
retry(err);
}
throw err;
})
}).then((value) => {
return value;
}, (err) => {
throw new Error(`retried requests failed with ${err.message}`);
});
}
export const rpWithRetry = new Proxy(rp, rpProxy);
当开发人员遇到麻烦时,我相信一个简单的工作解决方案摘录对他来说绰绰有余。后来他可以诊断出与该问题相关的根本原因和基本理解。
答案 10 :(得分:-4)
在微服务基础设施中(我知道不适合这个问题;))你不能使用:
server:
ssl:
trust-store: path-to-truststore...
trust-store-password: my-secret-password...
可以配置色带负载均衡器:
ribbon:
TrustStore: keystore.jks
TrustStorePassword : example
ReadTimeout: 60000
IsSecure: true
MaxAutoRetries: 1
这里https://github.com/rajaramkushwaha/https-zuul-proxy-spring-boot-app你可以找到一个工作样本。还有一个github讨论,但我再也找不到了。