我们有一个用SpringBoot编写的rest API,使用双向ssl Auth。当用户选择错误/过期的客户端证书时,我们希望发送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();
urls().forEach((url, guard) -> {
try {
((AuthorizedUrl)http.authorizeRequests().antMatchers(new String[]{url})).access(guard);
} catch (Exception var4) {
throw new UnsupportedOperationException("error");
}
});
下面是堆栈跟踪:
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状态代码?
发布于 2020-12-16 16:13:25
也许你可以试试控制器的建议:
@ControllerAdvice
class MyControllerExceptionHandler {
@ResponseStatus(HttpStatus.UNAUTHORIZED) // or whatever you want
@ExceptionHandler(SSLHandshakeException.class)
public void handleHandshakeException() {
// Nothing to do
}
}
发布于 2020-12-16 16:53:27
在您的安全配置中,添加以下行:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
//....
and().
.anonymous().disable()
.exceptionHandling()
.authenticationEntryPoint(new org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint("YourValue"));
}
它将返回HTTP 401:
Status Code: 401 Unauthorized
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: 0
//... other header values
WWW-Authenticate: YourValue
https://stackoverflow.com/questions/65319342
复制相似问题