如何使用 Rest-Assured 对来自公司代理后面的休息呼叫进行身份验证?

问题描述 投票:0回答:2

我尝试通过我们的公司代理呼叫休息服务,但不断收到回复:

407 Proxy Authentication Required. Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.

任何人都可以建议我可以尝试其他任何方法,或者支持 NTLM 的 RestAssured 替代方案吗?

这是我当前的代码:

    PreemptiveBasicAuthScheme auth = new PreemptiveBasicAuthScheme();
    auth.setUserName("my username");
    auth.setPassword("my password");

    // was getting desperate so tried adding this 
    System.setProperty("http.proxyHost", "XXXX");
    System.setProperty("http.proxyPort", "8080");
    System.setProperty("http.proxyUser", "my username");
    System.setProperty("http.proxyPassword", "my password");
    System.setProperty("https.proxyHost", "XXXX");
    System.setProperty("https.proxyPort", "8080");
    System.setProperty("https.proxyUser", "my username");
    System.setProperty("https.proxyPassword", "my password");

    Response r = RestAssured
            .given()
            // tried with and without this 
            .header("Proxy-Authorization", auth.generateAuthToken()) 
            .proxy("XXXX", 8080)
            .get(fullPath, key, key);
java rest rest-assured
2个回答
0
投票

这里有几个问题 - 第一个我已经解决了,第二个我仍然受阻。

设置代理身份验证只需设置正确的标头(如许多其他帖子中所述):

.header("Proxy-Authorization", auth.generateAuthToken())

阻碍我的是我正在调用一个在 https 而不是 http 上运行的服务,并且代理似乎没有被使用......所以回到绘图板。


0
投票

`

 public class AcceptAllCertificates {

  public static void main(String[] args) throws Exception {
    
   String proxyHost = "yourproxy.com";
    
   int proxyPort = 80;
    
    String proxyUser = "UserName";
    
    String proxyPassword = "blabla";
    
    String keystorePassword = "changeit";
    
    String truststorePassword = "changeit";
    
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
        }
    });



    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] {
        new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {}

            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }
    }, new java.security.SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());


    String url_get = "https://jira.com";
    System.out.println("DEBUG:: Trying to connect this url " + url_get);
    URL url = new URL(url_get);

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));



    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.setHostnameVerifier((hostname, session) - > true);

    String auth = proxyUser + ":" + proxyPassword;
    byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
    String authHeader = "Basic " + new String(encodedAuth);
    connection.setRequestProperty("Proxy-Authorization", authHeader);
    connection.connect();
    X509Certificate[] serverCerts1 = (X509Certificate[]) connection.getServerCertificates();
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    customKeystore.load(null, keystorePassword.toCharArray());
    try (OutputStream keystoreOutputStream = new FileOutputStream(".\\custom_keystore.jks")) {
        customKeystore.store(keystoreOutputStream, keystorePassword.toCharArray());
    }
    for (int i = 0; i < serverCerts1.length; i++) {
        X509Certificate cert = serverCerts1[i];
        String certFileName = "certificate_" + i + ".cer";
        try (FileWriter fw = new FileWriter(certFileName); PrintWriter pw = new PrintWriter(fw)) {
            pw.println("-----BEGIN CERTIFICATE-----");
            pw.println(Base64.getEncoder().encodeToString(cert.getEncoded()));
            pw.println("-----END CERTIFICATE-----");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Certificate Serial Number: " + cert.getSerialNumber());
        System.out.println("Certificate written to file: " + certFileName);
        System.out.println("----------------------------------------------");
        System.out.println("Adding the certificate file to my local Keystore");

        try {
            // Load the default cacerts keystore I have commented this lines because i dont have permission to update cacerts
            // String javaHome = System.getProperty("java.home");
            //String cacertsPath = javaHome + File.separator + "lib" + File.separator + "security" + File.separator + "cacerts";
            KeyStore truststore = customKeystore;
            try (InputStream in = new FileInputStream(".\\custom_keystore.jks")) {
                truststore.load( in , truststorePassword.toCharArray());
            }

            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            try (InputStream certInputStream = new FileInputStream(".\\" + certFileName)) {
                Certificate certificate = certFactory.generateCertificate(certInputStream);

                // Add the certificate to the keystore
                truststore.setCertificateEntry(certFileName, certificate);

                // Save the updated keystore
                try (OutputStream out = new FileOutputStream(".\\custom_keystore.jks")) {
                    truststore.store(out, truststorePassword.toCharArray());
                }


                System.out.println("Certificate imported successfully into custom_keytore.jks keystore.");

            }

            // Lets do a call now 
            Proxy proxy1 = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("UserName", "blabla".toCharArray());
                }
            });

            // ProxySpecification proxySpec = new ProxySpecification(proxy1);
            Response response = RestAssured.given()
                .header("Content-Type", "application/json; charset=utf-8")
                .header("Accept", "application/json")
                .header("Authorization", "Basic ZjY3E=")
                .proxy(ProxySpecification.host(proxyHost)
                    .withPort(proxyPort)
                    .withAuth("UserName", "blabla"))
                .trustStore(".\\custom_keystore.jks", "changeit")
                .when().get("https://jira.com");


            // Print the response
            System.out.println("API Response:");
            System.out.println(response.getBody().asString());

        } catch (Exception ex) {
            System.out.println("ERROR:: exception while adding certificates to the keystore" + ex);
        }
    }
}

} `

© www.soinside.com 2019 - 2024. All rights reserved.