Example usage for org.apache.http.impl.auth DigestScheme overrideParamter

List of usage examples for org.apache.http.impl.auth DigestScheme overrideParamter

Introduction

In this page you can find the example usage for org.apache.http.impl.auth DigestScheme overrideParamter.

Prototype

public void overrideParamter(final String name, final String value) 

Source Link

Usage

From source file:com.lxf.spider.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/* ww  w . j  a  va2 s.c  o m*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("httpbin.org", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//from w w w  .j a va 2s  . c o  m

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {

    HttpHost targetHost = new HttpHost("localhost", 80, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   w w  w.j  ava 2 s  . c  o  m
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("username", "password"));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(targetHost, digestAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("to target: " + targetHost);

        for (int i = 0; i < 3; i++) {
            HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:httpclient.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80),
            new UsernamePasswordCredentials("username", "password"));

    BasicHttpContext localcontext = new BasicHttpContext();
    // Generate DIGEST scheme object, initialize it and stick it to 
    // the local execution context
    DigestScheme digestAuth = new DigestScheme();
    // Suppose we already know the realm name
    digestAuth.overrideParamter("realm", "some realm");
    // Suppose we already know the expected nonce value 
    digestAuth.overrideParamter("nonce", "whatever");
    localcontext.setAttribute("preemptive-auth", digestAuth);

    // Add as the first request interceptor
    httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
    // Add as the last response interceptor
    httpclient.addResponseInterceptor(new PersistentDigest());

    HttpHost targetHost = new HttpHost("localhost", 80, "http");

    HttpGet httpget = new HttpGet("/");

    System.out.println("executing request: " + httpget.getRequestLine());
    System.out.println("to target: " + targetHost);

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            entity.consumeContent();/*from w  w  w .ja va 2  s .  c o  m*/
        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:org.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testDigestAuthenticatedPost() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Perform a HEAD, and extract the realm and nonce
    HttpHead head = new HttpHead(BASE_URL);
    head.addHeader("X-Requested-Auth", "Digest");
    HttpResponse headResponse = httpclient.execute(head);
    Header authHeader = headResponse.getHeaders("WWW-Authenticate")[0];
    String nonce = null;//from   w ww .  j av a 2  s .  c o  m
    String realm = null;
    for (HeaderElement element : authHeader.getElements()) {
        if ("nonce".equals(element.getName())) {
            nonce = element.getValue();
        } else if ("Digest realm".equals(element.getName())) {
            realm = element.getValue();
        }
    }
    // Build the post
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account",
            "CHANGE_ME");
    HttpPost post = new HttpPost(BASE_URL + "/capture-admin/agents/testagent");
    post.addHeader("X-Requested-Auth", "Digest");
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("state", "idle"));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    // Add the previously obtained nonce
    HttpContext localContext = new BasicHttpContext();
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", realm);
    digestAuth.overrideParamter("nonce", nonce);
    localContext.setAttribute("preemptive-auth", digestAuth);

    // Send the POST
    try {
        HttpResponse response = httpclient.execute(post, localContext);
        String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals("testagent set to idle", content);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java

@Test
public void testDigestAuth() throws Exception {
    URL url = new URL(urlStr);

    DefaultHttpClient httpclient = null;
    try {//from www .  jav a  2  s .c  o m
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        DigestHolder digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java

@Test
public void testDigestAuth() throws Exception {
    URL url = new URL(this.urlStr);

    DefaultHttpClient httpclient = null;
    try {//from  ww w.j  a v  a2  s.  c o  m
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        Digest digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java

/**
 * {@inheritDoc}//from w  w w.  j a va  2s.c  o m
 * @see org.opencastproject.loadtest.engage.util.remotetest.util.security.api.TrustedHttpClient#execute(org.apache.http.client.methods.HttpUriRequest)
 */
public HttpResponse execute(HttpUriRequest httpUriRequest) {
    // Add the request header to elicit a digest auth response
    httpUriRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);

    if ("GET".equalsIgnoreCase(httpUriRequest.getMethod())
            || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Run the request (the http client handles the multiple back-and-forth requests)
        try {
            return httpClient.execute(httpUriRequest);
        } catch (IOException e) {
            throw new TrustedHttpClientException(e);
        }
    }

    // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart
    // request), so we need to handle the details of the digest auth back-and-forth manually
    HttpRequestBase digestRequest;
    try {
        digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName());
    }
    digestRequest.setURI(httpUriRequest.getURI());
    digestRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    String[] realmAndNonce = getRealmAndNonce(digestRequest);

    if (realmAndNonce != null) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);

        // Set up the digest authentication with the required values
        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("realm", realmAndNonce[0]);
        digestAuth.overrideParamter("nonce", realmAndNonce[1]);

        // Add the authentication header
        try {
            httpUriRequest.addHeader(digestAuth.authenticate(creds, httpUriRequest));
        } catch (Exception e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }
    try {
        return httpClient.execute(httpUriRequest);
    } catch (Exception e) {
        // close the http connection(s)
        httpClient.getConnectionManager().shutdown();
        throw new TrustedHttpClientException(e);
    }
}

From source file:org.picketbox.http.test.config.ProtectedResourceManagerUnitTestCase.java

@Test
public void testDigestAuth() throws Exception {
    URL url = new URL(this.urlStr + "/onlyManagers/");

    DefaultHttpClient httpclient = null;
    try {//from w ww .  java 2  s .co m
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        Digest digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(404, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.picketbox.http.test.config.ProtectedResourceManagerUnitTestCase.java

@Test
public void testNotAuthorizedResource() throws Exception {
    URL url = new URL(this.urlStr + "confidentialResource");

    DefaultHttpClient httpclient = null;
    try {//from   w  w w  . ja  v  a2s  .c  om
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        Digest digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(403, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}