gpt4 book ai didi

java - 在 Spring Boot 中拦截 SSLHandshakeException

转载 作者:行者123 更新时间:2023-12-04 22:42:32 24 4
gpt4 key购买 nike

我们有一个使用 2-way ssl Auth 用 SpringBoot 编写的 rest API。
当用户选择错误/过期的客户端证书时,我们想发送 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 boot 配置 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 之前建立连接失败。
https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/ SSL/TLS 简介

关于java - 在 Spring Boot 中拦截 SSLHandshakeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65326068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com