我需要导入证书以便在Spring Boot应用程序中向外部服务发出http请求。
如何设置Spring Boot以实现此目的?
有很多信息可供参考,但我觉得有点混乱。似乎我只需要创建一个名为"truststore.jks"的密钥库,导入正确的证书,并在我的application.properties文件中添加一些条目即可。
我需要导入证书以便在Spring Boot应用程序中向外部服务发出http请求。
如何设置Spring Boot以实现此目的?
有很多信息可供参考,但我觉得有点混乱。似乎我只需要创建一个名为"truststore.jks"的密钥库,导入正确的证书,并在我的application.properties文件中添加一些条目即可。
keytool
生成一个cmd
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
回答所有问题。在第一个问题中:你的名字和姓氏是什么 改为 localhost
。
yourcertificate.crt
,请执行以下操作keytool -import -alias tomcat -file yourcertificate.crt -keystore keystore.p12 -storepass password
你会得到一个名为keystore.p12
的文件。
资源文件夹
中属性文件
中添加以下行# Define a custom port instead of the default 8080
server.port=8443
# Tell Spring Security (if used) to require requests over HTTPS
security.require-ssl=true
# The format used for the keystore
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password= {your password here}
# The alias mapped to the certificate
server.ssl.key-alias=tomcat
Config
类@Configuration
public class ConnectorConfig {
@Bean
public TomcatServletWebServerFactory 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(getHttpConnector());
return tomcat;
}
private Connector getHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
https://localhost:8443
访问现在您可以访问需要SSL认证的第三方服务。