HttpClient Authenticator with Umlauts

Viewed 89

How can I configure the Java 11 HttpClient Authenticator to encode the password correctly if the password contains (german) umlauts?

Here is the configuration

    String username = "testuser";
    String password = "täst";
    Authenticator authenticator = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    };
    HttpClient build = HttpClient.newBuilder()//
            .sslContext(disabledSslVerificationContext())//
            .authenticator(authenticator).build();
    String url = server + "/ping";

    String body = "";

    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)) //
            .header("Content-Type", "application/json") //
            .header("charset", "UTF-8") //
            .method("GET", BodyPublishers.ofString(body)).build();

I also tried setting .header("Content-Type", "text/html; charset=utf-8") but this also did not work.

If I add "password" to the header for debug purposes I see on the service that I receive t?st instead of täst.

How can I instruct the server to send the password in its correct form to the server?

[EDIT]

Debugging the code indicate that jdk.internal.net.http.AuthenticationFilter#response does not see my charset setting. This calls end up keeping isUTF8 to false, if I switch it to true in the debugger to true, the password is send correctly to the server.

for (String aval : authvals) {
        HeaderParser parser = new HeaderParser(aval);
        String scheme = parser.findKey(0);
        if (scheme.equalsIgnoreCase("Basic")) {
            authval = aval;
            var charset = parser.findValue("charset");
            isUTF8 = (charset != null && charset.equalsIgnoreCase("UTF-8"));
            break;
        }
    }

I still have not found the correct way of instructing the AuthenticationFilter to see my charset setting. Any advice?

1 Answers

Turns out that the ability to encode in utf-8 was only added in Java versions after Java 11 and is triggered by the server response header. So we would have to configure our server to return a certain element in its response. As this is currently not possible for us (as we have to use Java 11) we encoded the password to ISO_8859_1.

    String encodedPW = new String(password.getBytes(), StandardCharsets.ISO_8859_1.toString());
Related