У нас есть API для отдыха, написанный в SpringBoot с использованием двусторонней аутентификации ssl. Мы хотели бы отправить код состояния HTTP 401, когда пользователь выбирает неправильный/просроченный сертификат клиента.
Когда это происходит, я вижу исключение:
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.
Я подозревал это. Спасибо