【问题标题】:How to set a security context for java HttpUrlConnection?如何为 java HttpUrlConnection 设置安全上下文?
【发布时间】:2022-09-30 20:13:53
【问题描述】:

我正在使用 HttpUrlConnection 测试 HTTP 端点:

 HttpURLConnection httpCon = (HttpURLConnection) new URL(url).openConnection();
 httpCon.setDoOutput(true);
 httpCon.setRequestMethod(httpMethod);
 httpCon.setRequestProperty(\"Content-Type\", \"application/json\");
 requestHeaders.forEach(httpCon::setRequestProperty);

我还在最后添加了一个基本身份验证标头。

唯一的问题是有一个请求过滤器从请求授权的 SecurityContext 中读取 Principal。 到目前为止,我还没有找到在使用 HttpURLConnection 时设置 SecurityContext 和 Principal 的方法。

有没有办法这样做?

    标签: java rest testing


    【解决方案1】:

    我用来初始化一些 SSLContext (以验证应用程序定义的信任库 - 与客户端身份验证不直接相关),如下所示:

        // set truststore
        URL truststoreURL = getClass().getResource("client-truststore.jks");
        if (truststoreURL == null) {
            throw new IllegalStateException("Truststore not found in expected location " + truststoreURL);
        }
        try (InputStream truststoreStream = truststoreURL.openStream()) {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
            truststore.load(truststoreStream, "tgostatspassword".toCharArray());
            trustManagerFactory.init(truststore);
            sslContext = SSLContext.getInstance("TLS");
            KeyManager[] keyManagers = {};//if you have key managers;
    
            sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom());
        }
        catch (Exception e) {
            log.error("Could not initialize", e);
        }
    

    之后,我可以像这样打开连接:

    public URLConnection getConnection(URL url) throws IOException {
        URLConnection connection = url.openConnection();
    
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection sconnection = (HttpsURLConnection)connection;
            sconnection.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    
        return connection;
    }
    

    一个更新的答案是使用HttpClient,它是Builder。在那里你可以直接设置 SSLContext。它还支持身份验证器。

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 2021-04-21
      • 2023-03-12
      • 2011-05-14
      • 2014-05-11
      • 1970-01-01
      • 2013-11-25
      • 2012-12-12
      • 1970-01-01
      相关资源
      最近更新 更多