Search code examples
javaapache-commons-httpclient

Authenticating on a server using HTTP Commons Client


I am a complete beginner at this and I have been trying to make a connection with the server for quite some time

public class Test {

    public static void main(String[] args) throws ClientProtocolException, IOException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope("9.5.127.34", 80),
                new UsernamePasswordCredentials("root", "passw0rd"));

        String url_copied_from_firebug = "https://9.5.127.34/powervc/openstack/volume/v1/115e4ad38aef463e8f99991baad1f809//volumes/3627400b-cd98-46c7-a7e2-ebce587a0b05/restricted_metadata"
        HttpGet httpget = new HttpGet(url_copied_from_firebug);
        HttpResponse response = httpClient.execute(httpget);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {

            System.out.println(line);

            }   
        }
}

The error which I get when I try to run the code is

Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

I have tried changing the port number from 80 to 443 but it is not working. I think I am starting with it and might be missing a lot of things. Please point me in the right direction.

Thanx in advance.


Solution

  • Your problem is not HTTP authentication. Your http client could not verify the ssl certificate for the server with a certificate authority - this is probably because you are using a self-signed certificate.

    Look at the HttpClient documentation for instructions about how to customize your client to allow a self-signed certificate.

    Here is an example of creating an HttpClient that accepts all certificates and host names - just remember to use it with servers you trust:

        private DefaultHttpClient getSSLHttpClient(final URL url) throws RestClientException {
        try {
            final X509TrustManager trustManager = createTrustManager();
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{trustManager}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, createHostnameVerifier());
            AbstractHttpClient base = new DefaultHttpClient();
            ClientConnectionManager ccm = base.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme(HTTPS, url.getPort(), ssf));
            return new DefaultHttpClient(ccm, base.getParams());
        } catch (final Exception e) {
            throw new RestClientException(FAILED_CREATING_CLIENT, "Failed creating http client",
                    ExceptionUtils.getFullStackTrace(e));
        }
    }
    
    
    private X509TrustManager createTrustManager() {
        X509TrustManager tm = new X509TrustManager() {
    
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
    
            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) 
                    throws CertificateException {
            }
    
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) 
                    throws CertificateException {
            }
        };
        return tm;
    }
    
    
    private X509HostnameVerifier createHostnameVerifier() {
        X509HostnameVerifier verifier = new X509HostnameVerifier() {
    
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
    
            @Override
            public void verify(final String host, final String[] cns, final String[] subjectAlts) 
                    throws SSLException {
            }
    
            @Override
            public void verify(final String host, final X509Certificate cert) 
                    throws SSLException {
            }
    
            @Override
            public void verify(final String host, final SSLSocket ssl) 
                    throws IOException {
            }
        };
        return verifier;
    }