使用Spring Boot进行客户端证书身份验证

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

我该如何设置Spring Boot来做到这一点?

那里有很多信息,但我发现所有这些都令人困惑。似乎我可能只需要创建类似“ truststore.jks”密钥库的内容并导入正确的证书,然后将一些条目添加到我的application.properties中即可。


慕标琳琳
浏览 255回答 1
1回答

慕容森

首先生成一个自签名证书,keytool如果您还没有的话,请使用打开您的终端或 cmdkeytool -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。将此文件复制到您的 resources folder将以下行添加到您的properties文件中# Define a custom port instead of the default 8080server.port=8443# Tell Spring Security (if used) to require requests over HTTPSsecurity.require-ssl=true# The format used for the keystore server.ssl.key-store-type=PKCS12# The path to the keystore containing the certificateserver.ssl.key-store=classpath:keystore.p12# The password used to generate the certificateserver.ssl.key-store-password= {your password here}# The alias mapped to the certificateserver.ssl.key-alias=tomcat创建一个Config类,如下所示@Configurationpublic 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身份验证的第三项服务
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java