Apache HTTPClient DigestAuth 授权不起作用

问题描述

第一次访问服务器时,我的授权是成功的(虽然这是不正确的)。我不明白为什么这段代码中的摘要授权发生得这么早。 我正在使用以下解决方案:

import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.io.IoUtils;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.*;
import org.apache.http.ssl.SSLContextBuilder;
import org.testng.Assert;

import javax.net.ssl.*;

public class SOAPClientApache {


    private static final String URL = "https://httpbin.org/digest-auth/auth/user/passwd";


    private static final String PASSWORD = "passwd";    //passwd

    private static final String USER = "user";          //user

    public void run() throws Exception {

        HttpGet httpget = new HttpGet(URL);

        HttpHost target = new HttpHost(httpget.getURI().getHost(),443,"https");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USER,PASSWORD);
        credsProvider.setCredentials(
                new AuthScope(target.getHostName(),target.getPort()),credentials);

         CookieStore cookieStore = new BasicCookieStore();

        //SSL solution
        CloseableHttpClient httpclient
                = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setDefaultCredentialsProvider(credsProvider).build();  

        try {

            DigestScheme digestAuth = new DigestScheme();

            digestAuth.overrideParamter("qop","auth");
            digestAuth.overrideParamter("nc","0");
            digestAuth.overrideParamter("cnonce",DigestScheme.createCnonce());

            AuthCache authCache = new BasicAuthCache();
            authCache.put(target,digestAuth);

            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            CloseableHttpResponse response;

            response = httpclient.execute(target,httpget,localContext);

            //Массив headers (для тестов)
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header);
            }
            System.out.println();

            Map<String,String> wwwAuth = Arrays
                    .stream(response.getHeaders("WWW-Authenticate")[0]
                            .getElements())
                    .collect(Collectors.toMap(HeaderElement::getName,HeaderElement::getValue));

            //Выведем наш массивчик чтобы лицезреть
            for(Map.Entry<String,String> pair : wwwAuth.entrySet()){
                System.out.println(pair.getKey() + " = " + pair.getValue());
            }

            // the first call ALWAYS fails with a 401
            Assert.assertEquals(response.getStatusLine().getStatusCode(),401);

            digestAuth.overrideParamter("opaque",wwwAuth.get("opaque"));
            digestAuth.overrideParamter("nonce",wwwAuth.get("nonce"));
            digestAuth.overrideParamter("realm",wwwAuth.get("Digest realm"));

            Header authenticate = digestAuth.authenticate(credentials,localContext);
            httpget.addHeader(authenticate);


            response = httpclient.execute(target,localContext);

            // the 2nd call is the real deal
            Assert.assertEquals(response.getStatusLine().getStatusCode(),200);

            System.out.println(IoUtils
                    .toString(response.getEntity().getContent(),"utf-8"));


        } finally {
            httpclient.close();
        }
    }
}

当程序到达这一步时:

 Map<String,String> wwwAuth = Arrays
                        .stream(response.getHeaders("WWW-Authenticate")[0]
                                .getElements())
                        .collect(Collectors.toMap(HeaderElement::getName,HeaderElement::getValue));

然后“响应:HTTP / 1.1 200 OK”,程序退出异常

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)