使用Spring Boot进行客户端证书身份验证
我需要导入证书,以便向Spring Boot应用程序中的外部服务发出http请求.
I need to import a certificate in order to make a http request to an external service in a Spring Boot application.
我该如何设置Spring Boot?
How do I set up Spring Boot in order to do this?
那里有很多信息,但我发现所有这些都令人困惑.似乎我可能只需要创建一个类似"truststore.jks"密钥库的东西并导入正确的证书,然后将一些条目添加到我的application.properties中即可.
There's a lot of information out there but I'm finding it all a bit confusing. It seems as though I may just need to create something like a "truststore.jks" keystore and import the correct certificate, and and add some entries to my application.properties.
首先使用 keytool
生成自签名证书(如果您还没有的话)
打开您的终端或 cmd
Start by generating a self-signed certificate using keytool
if you don't already have one
Open your terminal or cmd
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
回答所有问题.在第一个问题中:您的名字和姓氏是 localhost
.
Answer all the questions. In the first question: what's your first name and last name put localhost
.
keytool -import -alias tomcat -file yourcertificate.crt -keystore keystore.p12 -storepass password
您将获得一个名为 keystore.p12
的文件.
You will get a file called 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身份验证的第三项服务
Now your application is accessible with https://localhost:8443
Now you can access your third service that asks you for ssl authentication