[英]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.