繁体   English   中英

在 Spring 引导中拦截 SSLHandshakeException

[英]Intercept SSLHandshakeException in Spring boot

我们有一个 rest API 使用 2 路 ssl Auth 在 SpringBoot 中编写。 当用户选择错误/过期的客户端证书时,我们想发送 401 HTTP 状态码。

当它发生时,我可以看到异常:

javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

API 启动正常,工作正常。 每当用户尝试调用我的 api 选择错误的客户端证书或无效时,就会发生异常。 在这种情况下,我想将 401 返回给调用者

Spring 启动配置了 Tomcat 和@EnableWebSecurity

http.x509().subjectPrincipalRegex("XXXXXX").userDetailsService(this.userDetailsService);
((RequiresChannelUrl)http.requiresChannel().anyRequest()).requiresSecure();
....
 http.exceptionHandling()
                    .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))


public TomcatConnectorCustomizer httpsConnectorCustomizer(....) {
    return (connector) -> {
        connector.setScheme("https");
        connector.setPort(port);
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        protocol.setSSLEnabled(true);
        protocol.setSecure(true);
        protocol.setPort(port);
        protocol.setClientAuth("optional");
        protocol.setKeystoreFile(...);
        protocol.setKeystorePass(...);
        protocol.setKeystoreType(...);
        protocol.setKeyAlias(...);
        protocol.setTruststoreFile(...);
        protocol.setTruststorePass(...);
        protocol.setTruststoreType(...);
    };
}

这里是堆栈跟踪:

DirectJDKLog.java:175 [] Handshake failed during wrap
javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
...
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
....
....
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)

浏览器显示:ERR_BAD_SSL_CLIENT_AUTH_CERT
是否可以在 SpringBoot 中捕获此异常并发送特定的 HTTP 状态码?

似乎异常在 java/tomcat 中很深,到目前为止我无法捕捉到它。

您将无法发送 HTTP 状态代码,因为在您开始谈论 HTTP之前建立连接失败。

有关 SSL / TLS 的介绍,请参阅https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM