Preemptive Basic Auth with Httpurlconnection

Preemptive Basic Auth with HttpUrlConnection?

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.

How to do Preemptive authentication using Java 11 HTTP client?

The HttpClient behaves in the same way than HttpURLConnection in what preemptive authentication is concerned: for basic authentication it will preemptively send the credentials if it finds them in its cache. However, the cache is populated after the first successful request (or more exactly after the response headers indicating that the authentication was successful are parsed).

If this is not satisfactory for you then a possibility is to handle authentication directly in your code by preemptively inserting the Authorization header in your request, and not setting any Authenticator.

Preemptive Basic authentication with Apache HttpClient 4

It's difficult to do this without passing a context through every time, but you can probably do it by using a request interceptor. Here is some code that we use (found from their JIRA, iirc):

// Pre-emptive authentication to speed things up
BasicHttpContext localContext = new BasicHttpContext();

BasicScheme basicAuth = new BasicScheme();
localContext.setAttribute("preemptive-auth", basicAuth);

httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

(...)

static class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

// If no auth scheme avaialble yet, try to initialize it
// preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
}

}

}

connect to a URL using Basic authentication in Java - java.net.ConnectException: Connection refused: connect

Be carefull to difference ProxyAuthentication from URI authentication.

Here you have an example for uri authentication [if u need to authenticate on the URI ] :

        BASE64Encoder encoder = new BASE64Encoder();//import sun.misc.BASE64Encoder;
String authString = name + ":" + password;
String authStringEncoded = encoder.encode(authString.getBytes());
setHeader("Authorization", "Basic " + authStringEncoded);

This for proxy authentication [ if u need to go out internet though a proxy ]:

            BASE64Encoder encoder = new BASE64Encoder();
String authString = name + ":" + password;
String authStringEncoded = encoder.encode(authString.getBytes());
setHeader("Proxy-Authorization", "Basic " + authStringEncoded);

Maybe, aslo, you can probe Apache utilities to get a correct encoded UserName / password

Something like this pseudo code:

Header  auth_header=
new DigestScheme().authenticate(new UsernamePasswordCredentials(authUser.asString(),
authPwd.asString()),
commonsHttpRequest,
new BasicHttpContext());

After, just:

urlConnection.setRequestProperty("Authorization", auth_header.getValue());

IOException in Basic Authentication for HTTP url

The code you are getting is HTTP 401 Unauthorized, which means that the server isn't interpreting your basic authentication properly.

Since you say that the curl command with the basic authentication you showed is working, I'll assume the problem is in your code.

It looks like you tried to follow this code.

The only error I can see (but I cannot test this to be sure) is that you just cast the byte[] to a String instead of encoding it with Base64.

So you should change this:

String authStringEnc = new String(authEncBytes);

to this:

String authStringEnc = Base64.getEncoder().encodeToString(authEncBytes);

Also, you want to change this:

byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());

to this:

byte[] authEncBytes = authString.getBytes();

byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);

How to set Basic Auth (Usernama and password) using java code

The basic auth header is generated from username:password using base 64,
the header authorization value could be generated like so:

Encoder encoder = Base64.getEncoder();
String originalString = username+":"+password;
String encodedString = encoder.encodeToString(originalString.getBytes());

String headerAthorization="Basic "+encodedString;

HttpClient and Basic Auth in URL

You need to set the header instead of passing it through the URL

var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));


Related Topics



Leave a reply



Submit