使用Java&amp ;;摘要验证Apache客户端:始终401未经授权

时间:2014-12-04 10:38:45

标签: java apache-httpclient-4.x digest-authentication

我正在尝试使用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", "me@kennethreitz.com");
        // // 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();
    }

}

1 个答案:

答案 0 :(得分:5)

@heaphach建议这是一个cookie问题。有线日志(显示日志类别org.apache.http.wire设置为调试)显示:
<< "Set-Cookie: fake=fake_value[\r][\n]" 但HttpClient从未接受过这个 并且不会在第二个GET请求中使用它,该请求包含带有摘要响应的完整“授权”标头。 因此,服务器只是忽略了摘要响应。

更新示例代码后(也称为Preemptive DIGEST authentication example) 使用下面显示的代码(从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包含一些代码来计算“nonce” 所以你可以使用
digestAuth.overrideParamter("nonce", calculateNonce());
{和org.apache.http.impl.auth.HttpAuthenticator不再显示错误消息“在挑战中缺少nonce。”

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());
}