Friday, April 12, 2013

HTTP Basic Authentication in Java - two different ways

We will see two different ways of authentication with java and . The connection is implemented with standard Sun/Oracle class

Solution 1: the more popular way, with Authenticator

            Authenticator.setDefault (new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
           String.format("Getting PasswordAuthentication with username %s and pass with lenght = %d", 

                    return new PasswordAuthentication ( 

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