简体   繁体   English

Apache http客户端样本无法进行摘要式身份验证

[英]Apache http client sample failing for Digest authentication

I am running the sample Apache hc (http client) for digest authentication. 我正在运行示例Apache hc(http客户端)进行摘要身份验证。 I didn't change anything, just using the provided sample: 我仅使用提供的示例就没有进行任何更改:

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 {

        // 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", "b2c603bb7c93cfa197945553a1044283");
        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();
    }
}

And I am getting: HTTP/1.1 401 UNAUTHORIZED 我得到:HTTP / 1.1 401未经授权

If I go direct to http://httpbin.org/digest-auth/auth/user/passwd in prompts me for user/passwd and then provides the page. 如果我直接转到http://httpbin.org/digest-auth/auth/user/passwd ,则会提示我输入user / passwd,然后提供页面。 So the website is working right. 因此,该网站正常运行。

Any idea what is wrong? 知道有什么问题吗? I have the latest version of the library. 我有该库的最新版本。

Fiddler Auth for browser (successful): 浏览器的Fiddler Auth(成功):

No Proxy-Authorization Header is present. 没有代理授权头。

Authorization Header is present: Digest username="user", realm="me@kennethreitz.com", nonce="8ada87344eb5a10bf810bcc211205c24", uri="/digest-auth/auth/user/passwd", response="ad22423e5591d14c90c6fe3cd762e64c", opaque="361645844d957289c4c8f3479f76269f", qop=auth, nc=00000001, cnonce="260d8ddfe64bf32e" 存在授权标头:摘要username =“ user”,realm =“ me@kennethreitz.com”,nonce =“ 8ada87344eb5a10bf810bcc211205c24”,uri =“ / digest-auth / auth / user / passwd”,response =“ ad22423e5591d14c90c6fe3cd762e64c”,不透明=“ 361645844d957289c4c8f3479f76269f”,qop = auth,nc = 00000001,cnonce =“ 260d8ddfe64bf32e”

Fiddler Auth for my code (failed): 我的代码的Fiddler Auth(失败):

No Proxy-Authorization Header is present. 没有代理授权头。

Authorization Header is present: Digest username="user", realm="me@kennethreitz.com", nonce="76af6c9c0a1f57ee5f0fcade2a5f758c", uri="http://httpbin.org/digest-auth/auth/user/passwd", response="745686e3f38ab40ce5907d41f91823e6", qop=auth, nc=00000001, cnonce="634b618d5c8ac9af", algorithm=MD5, opaque="fe84ce11c48a7b258490600800e5e6df" 存在授权标头:摘要用户名=“ user”,realm =“ me@kennethreitz.com”,nonce =“ 76af6c9c0a1f57ee5f0fcade2a5f758c”,uri =“ http://httpbin.org/digest-auth/auth/auth/user/passwd”,响应=“ 745686e3f38ab40ce5907d41f91823e6”,qop = auth,nc = 00000001,cnonce =“ 634b618d5c8ac9af”,算法= MD5,不透明=“ fe84ce11c48a7b258490600800e5e6df”

这段代码digestAuth.overrideParamter("realm", "some realm")应该进行一些更改。要用您的服务器"some realm"替换"some realm" 。请查看此问题

Ok I got it working. 好吧,我知道了。 You have to set a cookie too. 您也必须设置一个cookie。 Thanks to this post for the help. 感谢这篇文章的帮助。 The below code works - but only if you are not using Fiddler. 以下代码有效-但仅在您使用Fiddler的情况下。

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

        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
        cookie.setDomain("httpbin.org");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);

        // https://stackoverflow.com/questions/27291842/digest-auth-with-java-apache-client-always-401-unauthorized

        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()
                .setDefaultCookieStore(cookieStore)
                .setDefaultCredentialsProvider(credsProvider)
//              .setProxy(new HttpHost("127.0.0.1", 8888))
                .build();
        try {

            // 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", calculateNonce());
            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);
                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();
        }
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM