使用Spring Boot进行客户端证书认证

9

我需要导入证书以便在Spring Boot应用程序中向外部服务发出http请求。

如何设置Spring Boot以实现此目的?

有很多信息可供参考,但我觉得有点混乱。似乎我只需要创建一个名为"truststore.jks"的密钥库,导入正确的证书,并在我的application.properties文件中添加一些条目即可。


如果我理解正确的话,您需要SSL来连接另一个Web服务?因此,您的应用程序应该可以通过例如“https://localhost”进行访问。不是这样吗? - ISlimani
我需要一个特定的客户端证书来验证我向第三方服务发出的请求。 - simbro
1个回答

19

如果您还没有自签名证书,请使用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认证的第三方服务。


谢谢Dfor Tye。第三方服务已经给了我一个证书,我需要在所有请求中呈现它 - 我是否应该按照您的说明将此证书导入到我创建的密钥库中? - simbro
这正是我正在寻找的!再次感谢。 - simbro
这对我非常有帮助,但我遇到了一个问题,旧版本的Java默认创建JKS格式的密钥库,而不是本教程中所需的PCKS12格式。我使用了---> keytool -import -alias tomcat -file yourcertificate.crt -keystore keystore.p12 -storepass password -storetype PKCS12 - Kenny
2年过去了,它仍然很有用!谢谢!! - Parth Manaktala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接