Example usage for org.apache.http.auth AUTH WWW_AUTH

List of usage examples for org.apache.http.auth AUTH WWW_AUTH

Introduction

In this page you can find the example usage for org.apache.http.auth AUTH WWW_AUTH.

Prototype

String WWW_AUTH

To view the source code for org.apache.http.auth AUTH WWW_AUTH.

Click Source Link

Document

The www authenticate challange header.

Usage

From source file:securitydigest.TestDigestScheme.java

public void testDigestAuthenticationWithMultipleRealms() throws Exception {
    String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\"";
    String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\"";
    Credentials cred = new UsernamePasswordCredentials("username", "password");
    Credentials cred2 = new UsernamePasswordCredentials("uname2", "password2");

    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge1);
    HttpRequest request = new BasicHttpRequest("Simple", "/");
    AuthScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    Header authResponse = authscheme.authenticate(cred, request);

    Map<String, String> table = parseAuthResponse(authResponse);
    assertEquals("username", table.get("username"));
    assertEquals("realm1", table.get("realm"));
    assertEquals("/", table.get("uri"));
    assertEquals("abcde", table.get("nonce"));
    assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response"));

    authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge2);
    AuthScheme authscheme2 = new DigestScheme();
    authscheme2.processChallenge(authChallenge);
    authResponse = authscheme2.authenticate(cred2, request);

    table = parseAuthResponse(authResponse);
    assertEquals("uname2", table.get("username"));
    assertEquals("realm2", table.get("realm"));
    assertEquals("/", table.get("uri"));
    assertEquals("123546", table.get("nonce"));
    assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response"));
}

From source file:securitydigest.TestDigestScheme.java

/** 
 * Test digest authentication using the MD5-sess algorithm.
 *//*w ww .  j  av  a 2s.c  om*/
public void testDigestAuthenticationMD5Sess() throws Exception {
    // Example using Digest auth with MD5-sess

    String realm = "realm";
    String username = "username";
    String password = "password";
    String nonce = "e273f1776275974f1a120d8b92c5b3cb";

    String challenge = "Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", "
            + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess, " + "qop=\"auth,auth-int\""; // we pass both but expect auth to be used

    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);

    Credentials cred = new UsernamePasswordCredentials(username, password);
    HttpRequest request = new BasicHttpRequest("Simple", "/");

    AuthScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    Header authResponse = authscheme.authenticate(cred, request);
    String response = authResponse.getValue();

    assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes
    assertTrue(response.indexOf("qop=auth") > 0); // test for quotes

    Map<String, String> table = parseAuthResponse(authResponse);
    assertEquals(username, table.get("username"));
    assertEquals(realm, table.get("realm"));
    assertEquals("MD5-sess", table.get("algorithm"));
    assertEquals("/", table.get("uri"));
    assertEquals(nonce, table.get("nonce"));
    assertEquals(1, Integer.parseInt(table.get("nc"), 16));
    assertTrue(null != table.get("cnonce"));
    assertEquals("SomeString", table.get("opaque"));
    assertEquals("auth", table.get("qop"));
    //@TODO: add better check
    assertTrue(null != table.get("response"));
}

From source file:securitydigest.TestDigestScheme.java

/** 
 * Test digest authentication using the MD5-sess algorithm.
 *///from  ww  w  .j a v a  2 s .co  m
public void testDigestAuthenticationMD5SessNoQop() throws Exception {
    // Example using Digest auth with MD5-sess

    String realm = "realm";
    String username = "username";
    String password = "password";
    String nonce = "e273f1776275974f1a120d8b92c5b3cb";

    String challenge = "Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", "
            + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess";

    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);

    Credentials cred = new UsernamePasswordCredentials(username, password);

    HttpRequest request = new BasicHttpRequest("Simple", "/");

    AuthScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    Header authResponse = authscheme.authenticate(cred, request);

    Map<String, String> table = parseAuthResponse(authResponse);
    assertEquals(username, table.get("username"));
    assertEquals(realm, table.get("realm"));
    assertEquals("MD5-sess", table.get("algorithm"));
    assertEquals("/", table.get("uri"));
    assertEquals(nonce, table.get("nonce"));
    assertTrue(null == table.get("nc"));
    assertEquals("SomeString", table.get("opaque"));
    assertTrue(null == table.get("qop"));
    //@TODO: add better check
    assertTrue(null != table.get("response"));
}

From source file:securitydigest.TestDigestScheme.java

/** 
 * Test digest authentication with invalud qop value
 *///from w  w  w .  j a  v  a  2  s .  c  om
public void testDigestAuthenticationMD5SessInvalidQop() throws Exception {
    // Example using Digest auth with MD5-sess

    String realm = "realm";
    String nonce = "e273f1776275974f1a120d8b92c5b3cb";

    String challenge = "Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", "
            + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess, " + "qop=\"jakarta\""; // jakarta is an invalid qop value

    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);

    try {
        AuthScheme authscheme = new DigestScheme();
        authscheme.processChallenge(authChallenge);
        fail("MalformedChallengeException exception expected due to invalid qop value");
    } catch (MalformedChallengeException e) {
    }
}

From source file:securitydigest.TestDigestScheme.java

public void testDigestAuthenticationWithStaleNonce() throws Exception {
    String challenge = "Digest realm=\"realm1\", "
            + "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", stale=\"true\"";
    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    AuthScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);

    assertFalse(authscheme.isComplete());
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

private void put(int wait, Resource resource, File source, HttpEntity httpEntity, String url)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    // preemptive for put
    // TODO: is it a good idea, though? 'Expect-continue' handshake would serve much better

    Repository repo = getRepository();/*from   w  w  w . j  a  va  2s .com*/
    HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol());
    AuthScope targetScope = getBasicAuthScope().getScope(targetHost);

    if (credentialsProvider.getCredentials(targetScope) != null) {
        BasicScheme targetAuth = new BasicScheme();
        try {
            targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive"));
            authCache.put(targetHost, targetAuth);
        } catch (MalformedChallengeException ignore) {
        }
    }

    //Parent directories need to be created before posting
    try {
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (HttpException he) {
        fireTransferError(resource, he, TransferEvent.REQUEST_GET);
    }

    HttpPut putMethod = new HttpPut(url);

    firePutStarted(resource, source);

    try {
        putMethod.setEntity(httpEntity);

        CloseableHttpResponse response = execute(putMethod);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            String reasonPhrase = ", ReasonPhrase: " + response.getStatusLine().getReasonPhrase() + ".";
            fireTransferDebug(url + " - Status code: " + statusCode + reasonPhrase);

            // Check that we didn't run out of retries.
            switch (statusCode) {
            // Success Codes
            case HttpStatus.SC_OK: // 200
            case HttpStatus.SC_CREATED: // 201
            case HttpStatus.SC_ACCEPTED: // 202
            case HttpStatus.SC_NO_CONTENT: // 204
                break;
            // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user"
            case HttpStatus.SC_MOVED_PERMANENTLY: // 301
            case HttpStatus.SC_MOVED_TEMPORARILY: // 302
            case HttpStatus.SC_SEE_OTHER: // 303
                put(resource, source, httpEntity, calculateRelocatedUrl(response));
                return;
            case HttpStatus.SC_FORBIDDEN:
                fireSessionConnectionRefused();
                throw new AuthorizationException("Access denied to: " + url + reasonPhrase);

            case HttpStatus.SC_NOT_FOUND:
                throw new ResourceDoesNotExistException("File: " + url + " does not exist" + reasonPhrase);

            case SC_TOO_MANY_REQUESTS:
                put(backoff(wait, url), resource, source, httpEntity, url);
                break;
            //add more entries here
            default: {
                TransferFailedException e = new TransferFailedException(
                        "Failed to transfer file: " + url + ". Return code is: " + statusCode + reasonPhrase);
                fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
                throw e;
            }
            }

            firePutCompleted(resource, source);

            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (HttpException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (InterruptedException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException(e.getMessage(), e);
    }

}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

private void put(int wait, Resource resource, File source, HttpEntity httpEntity, String url)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    //Parent directories need to be created before posting
    try {//from   w  w  w .  j  a va 2s . c om
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (HttpException he) {
        fireTransferError(resource, he, TransferEvent.REQUEST_GET);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    // preemptive for put
    // TODO: is it a good idea, though? 'Expect-continue' handshake would serve much better
    Repository repo = getRepository();
    HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol());
    AuthScope targetScope = getBasicAuthScope().getScope(targetHost);

    if (credentialsProvider.getCredentials(targetScope) != null) {
        BasicScheme targetAuth = new BasicScheme();
        try {
            targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive"));
            authCache.put(targetHost, targetAuth);
        } catch (MalformedChallengeException ignore) {
            // ignore
        }
    }

    HttpPut putMethod = new HttpPut(url);

    firePutStarted(resource, source);

    try {
        putMethod.setEntity(httpEntity);

        CloseableHttpResponse response = execute(putMethod);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            String reasonPhrase = ", ReasonPhrase: " + response.getStatusLine().getReasonPhrase() + ".";
            fireTransferDebug(url + " - Status code: " + statusCode + reasonPhrase);

            // Check that we didn't run out of retries.
            switch (statusCode) {
            // Success Codes
            case HttpStatus.SC_OK: // 200
            case HttpStatus.SC_CREATED: // 201
            case HttpStatus.SC_ACCEPTED: // 202
            case HttpStatus.SC_NO_CONTENT: // 204
                break;
            // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect
            // the request unless it can be confirmed by the user"
            case HttpStatus.SC_MOVED_PERMANENTLY: // 301
            case HttpStatus.SC_MOVED_TEMPORARILY: // 302
            case HttpStatus.SC_SEE_OTHER: // 303
                put(resource, source, httpEntity, calculateRelocatedUrl(response));
                return;
            case HttpStatus.SC_FORBIDDEN:
                fireSessionConnectionRefused();
                throw new AuthorizationException("Access denied to: " + url + reasonPhrase);

            case HttpStatus.SC_NOT_FOUND:
                throw new ResourceDoesNotExistException("File: " + url + " does not exist" + reasonPhrase);

            case SC_TOO_MANY_REQUESTS:
                put(backoff(wait, url), resource, source, httpEntity, url);
                break;
            //add more entries here
            default:
                TransferFailedException e = new TransferFailedException(
                        "Failed to transfer file: " + url + ". Return code is: " + statusCode + reasonPhrase);
                fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
                throw e;
            }

            firePutCompleted(resource, source);

            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (HttpException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (InterruptedException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException(e.getMessage(), e);
    }

}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

protected CloseableHttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException {
    setHeaders(httpMethod);/*from  w  ww  . j av a 2 s. co m*/
    String userAgent = getUserAgent(httpMethod);
    if (userAgent != null) {
        httpMethod.setHeader(HTTP.USER_AGENT, userAgent);
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    // WAGON-273: default the cookie-policy to browser compatible
    requestConfigBuilder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);

    Repository repo = getRepository();
    ProxyInfo proxyInfo = getProxyInfo(repo.getProtocol(), repo.getHost());
    if (proxyInfo != null) {
        HttpHost proxy = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort());
        requestConfigBuilder.setProxy(proxy);
    }

    HttpMethodConfiguration config = httpConfiguration == null ? null
            : httpConfiguration.getMethodConfiguration(httpMethod);

    if (config != null) {
        ConfigurationUtils.copyConfig(config, requestConfigBuilder);
    } else {
        requestConfigBuilder.setSocketTimeout(getReadTimeout());
    }

    localContext.setRequestConfig(requestConfigBuilder.build());

    if (config != null && config.isUsePreemptive()) {
        HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol());
        AuthScope targetScope = getBasicAuthScope().getScope(targetHost);

        if (credentialsProvider.getCredentials(targetScope) != null) {
            BasicScheme targetAuth = new BasicScheme();
            targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive"));
            authCache.put(targetHost, targetAuth);
        }
    }

    if (proxyInfo != null) {
        if (proxyInfo.getHost() != null) {
            HttpHost proxyHost = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort());
            AuthScope proxyScope = getProxyBasicAuthScope().getScope(proxyHost);

            String proxyUsername = proxyInfo.getUserName();
            String proxyPassword = proxyInfo.getPassword();
            String proxyNtlmHost = proxyInfo.getNtlmHost();
            String proxyNtlmDomain = proxyInfo.getNtlmDomain();

            if (proxyUsername != null && proxyPassword != null) {
                Credentials creds;
                if (proxyNtlmHost != null || proxyNtlmDomain != null) {
                    creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain);
                } else {
                    creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
                }

                credentialsProvider.setCredentials(proxyScope, creds);
                BasicScheme proxyAuth = new BasicScheme();
                proxyAuth.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC preemptive"));
                authCache.put(proxyHost, proxyAuth);
            }
        }
    }

    return CLIENT.execute(httpMethod, localContext);
}

From source file:io.fabric8.devops.connector.DevOpsConnector.java

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    if (Strings.isNullOrBlank(gerritUser)) {
        gerritUser = "admin";
    }/*from   ww  w  .j av a  2  s .c  o m*/
    if (Strings.isNullOrBlank(gerritPwd)) {
        gerritPwd = "secret";
    }

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpClient httpclientPost = HttpClients.createDefault();
    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;
    HttpGet httpget = new HttpGet(GERRIT_URL);
    System.out.println("Requesting : " + httpget.getURI());

    try {
        //Initial request without credentials returns "HTTP/1.1 401 Unauthorized"
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getStatusLine());

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // Get current current "WWW-Authenticate" header from response
            // WWW-Authenticate:Digest realm="My Test Realm", qop="auth",
            // nonce="cdcf6cbe6ee17ae0790ed399935997e8", opaque="ae40d7c8ca6a35af15460d352be5e71c"
            Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
            System.out.println("authHeader = " + authHeader);

            DigestScheme digestScheme = new DigestScheme();

            //Parse realm, nonce sent by server.
            digestScheme.processChallenge(authHeader);

            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(gerritUser, gerritPwd);
            httpget.addHeader(digestScheme.authenticate(creds, httpget, null));

            HttpPost httpPost = new HttpPost(GERRIT_URL);
            httpPost.addHeader(digestScheme.authenticate(creds, httpPost, null));
            httpPost.addHeader("Content-Type", "application/json");

            CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
            createRepoDTO.setDescription(gerritGitRepoDescription);
            createRepoDTO.setName(repoName);
            createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(createRepoDTO);

            HttpEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclientPost.execute(httpPost, responseHandler);
            System.out.println("responseBody : " + responseBody);
        }

    } catch (MalformedChallengeException e) {
        e.printStackTrace();
    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        System.out.println("Gerrit Server is not responding");
    } catch (HttpResponseException e) {
        System.out.println("Response from Gerrit Server : " + e.getMessage());
        throw new Exception("Repository " + repoName + " already exists !");
    } finally {
        httpclient.close();
        httpclientPost.close();
    }
}

From source file:org.apache.http.impl.auth.TestBasicScheme.java

@Test(expected = MalformedChallengeException.class)
public void testBasicAuthenticationWithNoRealm() throws Exception {
    final String challenge = "Basic";
    final Header header = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final AuthScheme authscheme = new BasicScheme();
    authscheme.processChallenge(header);
}