简体   繁体   中英

Using Apache HTTP Client without passing the credentials as String?

Following an audit on our Swing application, it appears that some passwords of our users remain in memory long after they logged in or even out.

One of the causes seem to be that Apache HttpClient's UsernamePasswordCredentials stores the password as a final String , preventing to programmatically wipe it from memory (see Why is char[] preferred over String for passwords? ).

However since the Credentials interface it implements has a String getPassword() method, it does not seem possible to avoid the conversion to a String at some point.

Is there another way to avoid passing the password around as a String in this case?

We are using HttpClient 4.0.3 but it does not seem like this has changed in more recent versions.

Apache says that initializing UsernamePasswordCredentials with the password String is deprecated

UsernamePasswordCredentials(String usernamePassword)
Deprecated.
(4.5) will be replaced with String, char[] in 5.0

UsernamePasswordCredentials(String userName, String password)
The constructor with the username and password arguments.

https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/auth/UsernamePasswordCredentials.html

Are you using the latest version of the library? If so, they would not store the password as String but rather char[].

In the end I implemented the workaround proposed by Edd in the comments of his answer .

char[] password = …
final Credentials credentials = new UsernamePasswordCredentials(username, null) {
    @Override
    public String getPassword() {
        // AKCTAT-3791: this helps the GC to clear the String from the memory, as it will be used and dismissed immediately
        // Unfortunately Apache HTTP Client does not allow to pass the byte[] directly
        return new String(password);
    }
};
httpClient.getCredentialsProvider().setCredentials(ANY_AUTHSCOPE, (Credentials) auth.getCredentials());
// ... (do stuff with httpClient)
Arrays.fill(password, '\0');

It appears the GC removes it very quickly from memory, but it is still only a workaround without guarantee.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM