簡體   English   中英

Spring 引導捕獲 SSLHandshakeException

[英]Spring boot catch SSLHandshakeException

我們有一個 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();

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狀態碼?

也許您可以嘗試 controller 建議:

@ControllerAdvice
class MyControllerExceptionHandler {

    @ResponseStatus(HttpStatus.UNAUTHORIZED)  // or whatever you want
    @ExceptionHandler(SSLHandshakeException.class)
    public void handleHandshakeException() {
        // Nothing to do
    }
}

也許這里這里發布的解決方案可以幫助你

在您的安全配置中添加以下行:

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM