Дайджест-аутентификация с клиентом Java и Apache: Всегда 401 Неавторизованный

Я пытаюсь реализовать дайджест-аутентификацию с помощью HTTP-клиента, но на данный момент это не работает.

Кто-нибудь может проверить правильность этого кода? Для тестирования я использую http://httpbin.org/, но получаю только HTTP/1.1 401 Unauthorized.

Вот пример кода:

private static void doDigestAuth() throws ClientProtocolException,
    IOException,
    AuthenticationException,
    MalformedChallengeException
{

    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 {

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

        // 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", "[email protected]");
        // // Suppose we already know the expected nonce value
        // digestAuth.overrideParamter("nonce", Long.toString(new SecureRandom().nextLong(), 36));
        // qop-value = "auth" | "auth-int" | token
        digestAuth.overrideParamter("qop", "auth");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        // context.setAuthSchemeRegistry(authRegistry);
        context.setAuthCache(authCache);

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(httpget, context);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();
                InputStream instream = entity.getContent();
                // Header contentCncoding = entity .getContentEncoding();
                String contentString = IOUtils.toString(instream, null);
                System.out.println("ContentString:" + contentString);
                AuthState proxyAuthState = context.getProxyAuthState();
                System.out.println("Proxy auth state: " + proxyAuthState.getState());
                System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());
                System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());
                AuthState targetAuthState = context.getTargetAuthState();
                System.out.println("Target auth state: " + targetAuthState.getState());
                System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());
                System.out.println("Target auth credentials: " + targetAuthState.getCredentials());
                EntityUtils.consume(response.getEntity());
            }
            finally {
                response.close();
            }
        }
    }
    finally {
        httpclient.close();
    }

}

person user3280180    schedule 04.12.2014    source источник
comment
не могли бы вы решить эту проблему?   -  person Goot    schedule 26.04.2015
comment
Может быть, для httpbin требуется файл cookie, а без файла cookie он отвечает 401?   -  person heaphach    schedule 12.05.2015
comment
Возможный дубликат Apache HttpClient Digest аутентификации   -  person Alex R    schedule 28.10.2018


Ответы (1)


Как предположил @heaphach, это была проблема с файлами cookie. Проводной журнал (показан с категорией журнала org.apache.http.wire, установленной для отладки) показывает:
<< "Set-Cookie: fake=fake_value[\r][\n]"
но HttpClient никогда не берет это и не использует во втором запросе GET, содержащем полный заголовок "Авторизация" с дайджестом -отклик. Как следствие, сервер просто игнорирует дайджест-ответ.

После обновления кода примера (также известного как Пример упреждающей DIGEST-аутентификации) с кодом, показанным ниже (скопировано из управления состоянием HTTP tutorial), сервер ответил "200 OK".

CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
cookie.setDomain("httpbin.org");
cookie.setPath("/");
cookieStore.addCookie(cookie);
CloseableHttpClient httpclient = HttpClients.custom()
        .setDefaultCookieStore(cookieStore)
        .setDefaultCredentialsProvider(credsProvider)
        .build();

Я также наткнулся на gist, содержащий некоторый код для вычисления "одноразового номера", поэтому вы можете использовать
digestAuth.overrideParamter("nonce", calculateNonce());
и org.apache.http.impl.auth.HttpAuthenticator больше не показывает сообщение об ошибке "отсутствует одноразовый номер в вызове".

public static synchronized String calculateNonce() {

    Date d = new Date();
    SimpleDateFormat f = new SimpleDateFormat("yyyy:MM:dd:hh:mm:ss");
    String fmtDate = f.format(d);
    Random rand = new Random(100000);
    Integer randomInt = rand.nextInt();
    return org.apache.commons.codec.digest.DigestUtils.md5Hex(fmtDate + randomInt.toString());
}
person vanOekel    schedule 06.11.2015
comment
В httpclient v4.5.3 и v4.5.4 есть некоторые изменения, касающиеся этой проблемы. - person user85155; 27.05.2019