异常无法在Spring MVC中验证目标的证书


问题内容

我正在尝试使用我的用户名和密码从jira服务器获取问题详细信息,但我收到一条ssl错误,提示无法验证证书

那么如何验证证书

网址:http:local / 8080 / frr / hello

出现错误:

嵌套的异常是org.springframework.web.client.ResourceAccessException:GET请求的I / O错误为


https://jira.example.com/rest/api/2/issue/id
”:

sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到到请求目标的有效认证路径;嵌套异常为javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:找不到根本原因的有效证书路径],其根本原因是sun.security。
.provider.certpath.SunCertPathBuilderException:无法找到到请求目标的有效证书路径

我的Service.class代码

@Controller
public class Service{


    @RequestMapping("/hello")


     public String Data(ModelMap model){

        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> result = restTemplate.exchange("https://jira.example.com/rest/api/2/issue/id",  HttpMethod.GET, new HttpEntity<String>(createHeaders("username", "password")), String.class);

        model.addAttribute("message", result);


        return "helloworld";
    }

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders createHeaders( String username, String password ){
        HttpHeaders header =  new HttpHeaders();
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")) );
        String base64Creds = "Basic " + new String( encodedAuth );
        header.add("Authorization", "Basic " + base64Creds);
        return header;
    }   
}

问题答案:

您面临的问题是应用程序无法验证您尝试连接的外部服务器,因为 其证书不受信任

简而言之是:

  • 您的应用程序尝试通过安全(HTTPS)通道连接到Jira实例
  • 建立安全连接,应用程序将下载证书
  • 应用程序通过尝试将其追溯到已知的CA(保存在JRE证书存储中)来检查证书的有效性
  • 证书检查失败,因为证书是自签名的(最有可能)或已过期等。

如果此Jira实例是本地的(由您的公司托管),则完全不可能拥有自签名证书。在这种情况下,证书不是由已知的CA颁发的,因此,如果您希望信任它,则
需要手动注册它

首先获得证书:

openssl s_client -connect jira.example.com:443 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > public.crt

然后将其导入到您自己的密钥库中:

$JAVA_HOME/keytool -import -alias <server_name> -keystore $JAVA_HOME/lib/security/cacerts -file public.crt

注意:以上命令适用于Unix环境。在Windows下,我建议从命令行使用类似的openssl,但是也有用于相同目的的GUI工具。