I am using the Authenticator class in Java for proxy authentication in my application. The authentication works correctly when I enter the wrong credentials initially, as it throws an error. However, once I enter the correct credentials, subsequent attempts with incorrect credentials still succeed. It seems like the correct credentials are being cached and reused even when I want to authenticate with new credentials.
Code Example:
Here’s a simplified version of my code:
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
After the initial correct authentication, I can’t seem to override the credentials with wrong ones.
Attempts to Resolve:
-
I tried setting the Authenticator to null after each attempt:
Authenticator.setDefault(null);
-
I also tried creating a new Authenticator instance for each authentication attempt to prevent credential caching.
Questions:
- Why are the credentials being cached even after setting the Authenticator to null?
- How can I ensure that the Authenticator doesn’t cache credentials and each authentication attempt uses fresh credentials?
Additional Information:
- The application is a simple Java console application.
- The proxy requires basic HTTP authentication.
I’m running Java version 11.0.19 on Windows 10.