Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preemptive Basic Auth with HttpUrlConnection?

What is the best way to use preemptive basic http authentication using HttpUrlConnection. (Assume for now I can't use HttpClient).

EDIT for clarification: I'm setting the un/pw correctly in the request header using Base64 encoding. Are there any additional flags or properties that need to be set, or is the fact that I'm setting the basic auth headers for the request all that is needed for preemptive basic auth?

like image 874
Dave Sims Avatar asked Aug 11 '11 01:08

Dave Sims


People also ask

How do I pass basic authentication in HttpURLConnection?

As mentioned previously, we have to use “Authorization” as our header and “Basic ” + encoded credentials as our value: connection. setRequestProperty("Authorization", authHeaderValue); Finally, we need to actually send the HTTP request, like for example by calling getResponseCode().

What is preemptive basic authentication?

Preemptive basic authentication is the practice of sending http basic authentication credentials (username and password) before a server replies with a 401 response asking for them. This can save a request round trip when consuming REST apis which are known to require basic authentication.

How do I pass HttpURLConnection header?

URL url = new URL(urlToConnect); HttpURLConnection httpUrlConnection = (HttpURLConnection) url. openConnection(); Step 2: Add headers to the HttpURLConnection using setRequestProperty method.


1 Answers

If you are using Java 8 or later, java.util.Base64 is usable:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));  //Java 8 connection.setRequestProperty("Authorization", "Basic "+encoded); 


Then use the connection as normal.

If you're using Java 7 or lower, you'll need a method to encode a String to Base64, such as:

byte[] message = (username+":"+password).getBytes("UTF-8"); String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message); 

Yes, that's all you have to do in order to use Basic Auth. The code above to set the Request Property should be done immediately after opening the connection and before getting the Input or Output streams.

like image 184
dontocsata Avatar answered Sep 28 '22 20:09

dontocsata