Solution 1: the more popular way, with Authenticator
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
log.info( String.format("Getting PasswordAuthentication with username %s and pass with lenght = %d",
userStr,
passStr.length())
);
return new PasswordAuthentication (
userStr,
passStr.toCharArray());
}
Solution 2: the direct authentication injection, according http-basic standard:
import javax.xml.bind.DatatypeConverter; // standard class for Java 1.6, no additional jar needed
...
String encryptedUserPass = DatatypeConverter.printBase64Binary(
( userStr +":" + passStr ).getBytes()
);
connection.setRequestProperty ("Authorization", "Basic " + encryptedUserPass );
Why the popular way is not fine?
- it uses same authenticator for all connection. In multitheaded and multi-connectioned applications it could cause problems - same authentication for different servers. I could not found a way of setting an Authenticatotor just for my connection.
- two requests for each my request. The first is initialised with no authentication, and when server says that it needs, the java library sends the second one, with user+pass; For debugging purposes it is not good.
No comments:
Post a Comment