Reputation: 153
I am trying to access an API via httpGet with basic auth. My code is:
byte[] encodedBytes = Base64.getEncoder().encode("user:pass".getBytes());
HttpGet httpget = new HttpGet("https://app.feedcheck.co/api/reviews");
httpget.setHeader("Authorization", "Basic " + encodedBytes);
System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String apiOutput = EntityUtils.toString(entity);
System.out.println(apiOutput);
In postman I get the response I expect but when running the program in Eclipse it returns:
Could not verify your access level for that URL. You have to login with proper credentials
When doing the request in Python with code:
import requests
from requests.auth import HTTPBasicAuth
r = requests.get('https://app.feedcheck.co/api/reviews', auth=HTTPBasicAuth('user', 'pass'))
print(r.text)
it returns the same as Postman. Can anyone help me with this? What am I doing wrong?
Upvotes: 5
Views: 23575
Reputation: 178
I have just been playing with Basic auth, Digest auth, SSL accepting all certs, and also being strict. This test code can do all of those and also uses HttpClient like the op. It's commented and the "if/else" blocks clearly allow you to select the scenario you are trying to solve.
package com.myorg.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
public class DigestTest {
// Test get URL.
static String sGetURL = "https://192.168.0.1/info";
// Test post URL
static String sPostURL = "https://192.168.0.1/set";
// Fetch a URL
// Authentication
// Assumes user and password are required
// Will determine if Basic or Digest authentication is needed based on response header
// HTTP Verb
// If "postParams" is not null, will use POST, otherwise will use GET
//
public void URLFetch(String sURL, String sUser, String sPW, List<NameValuePair> postParams,
boolean bIgnoreCerts) {
try {
// Create empty objects for POST and GET since we don't know which we'll use
// below
HttpPost httppost = null;
HttpGet httpget = null;
// Crate a URL object
URL url = new URL(sURL);
// Now create the HttpHost object from the URL
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
// Here we need an HTTP client either with or without the SSLContext that
// ignores certs
CloseableHttpClient httpClient = null;
if (bIgnoreCerts) {
// Create an SSL context that accepts certs regardless of name match or trust (for self-signed)
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true)
.build();
httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",
new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()))
.build();
} else {
httpClient = HttpClients.createDefault();
}
// The HttpCLientContext
final HttpClientContext context = HttpClientContext.create();
// We'll need to allocate the response object below depending on type
CloseableHttpResponse response = null;
try {
if (postParams != null) {
httppost = new HttpPost(sURL);
// Get the response
response = httpClient.execute(targetHost, httppost, context);
} else {
httpget = new HttpGet(sURL);
// Get the response
response = httpClient.execute(targetHost, httpget, context);
}
} catch (SSLHandshakeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Add credentials for digest header
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
// Change to just pass user and password
Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
HeaderElement[] element = authHeader.getElements();
if (element.length != 0) {
AuthCache authCache = new BasicAuthCache();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(sUser, sPW));
if (element[0].getName().startsWith("Basic")) {
authCache.put(targetHost, new BasicScheme());
} else if (element[0].getName().startsWith("Digest")) {
DigestScheme digestScheme = new DigestScheme();
digestScheme.overrideParamter("realm", "thermostat");
digestScheme.processChallenge(authHeader);
authCache.put(targetHost, digestScheme);
}
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
}
}
// This ensures that the resource gets cleaned up
response = null;
if (postParams != null) {
httppost = new HttpPost(sURL);
if (postParams != null) {
httppost.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
// Get the response
response = httpClient.execute(targetHost, httppost, context);
}
} else {
httpget = new HttpGet(sURL);
// Get the response
response = httpClient.execute(targetHost, httpget, context);
}
// Get the data
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
try {
try (BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(sURL + " : " + inputLine);
}
EntityUtils.consume(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MalformedURLException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
| MalformedChallengeException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// Main, takes 4 arguments (see println below)
public static void main(String[] args) {
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("away", "1"));
DigestTest d = new DigestTest();
d.URLFetch(sPostURL, "user", "password", postParameters, false);
d.URLFetch(sGetURL, "user", "password", null, true);
}
}
Upvotes: 0
Reputation: 624
Check this. It worked for me.
try {
String webPage = "http://192.168.1.1";
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 7