使用apache httpclient进行摘要式身份验证

时间:2017-02-10 12:29:51

标签: java apache authentication

我正在使用apache HttpClient5实现一个简单的(不是抢占式,而不是通过代理)摘要式身份验证。文档很少,但应该相当简单。

但是,我一直得到401作为回应,而且我不清楚我是如何确定的,如果这是因为我的实施错误,或者401是真的。使用过的凭证肯定是正确的,我查了一下。

所以我的问题是:

  1. 这段代码基本上是正确的还是我遗漏了一些东西(例如我是否必须自己处理挑战。我假设httpClient为我做了这个。)
  2. 如果由于处理错误而导致处理挑战失败,那么除了401之外,我是否应该在日志中获得更多信息。
  3. digest {}身份验证错误:遗漏领域:在认证过程的第一个句子中这是正常的,还是我应该抢先提供领域?我假设httpClient从服务器的挑战中得到了这个,并且可以在第二次调用中提供它。另一方面,它被标记为“严重”......
  4. ..这是代码段.. ..我清理了一些代码,因此它只代表摘要认证的行。 ..或许密切联系的声明会肆虐?

                HttpRequestBase request = request = new HttpGet(params.getRequestUrl());
                // .....
                // then setting requestconfig, headers, body, contenttype etc.
                // .....
                HttpClientContext localContext = HttpClientContext.create();
                // set authentication (just a POJO with a username and a password)
                final HttpBasicAuthentication authentication = params.getAuthentication();
                URI uri = request.getURI();
                String host = uri.getHost();
                int port = uri.getPort();
                String scheme = uri.getScheme();
                HttpHost target = new HttpHost(host,port,scheme);
    
                char[] password = authentication.getPassword().toCharArray();
                final org.apache.hc.client5.http.auth.Credentials creds = new org.apache.hc.client5.http.auth.UsernamePasswordCredentials(authentication.getUsername(), password);
                BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
                    cP.setCredentials(org.apache.hc.client5.http.auth.AuthScope.ANY, creds); 
                localContext.setCredentialsProvider(cP);
    
                AuthCache authCache = new BasicAuthCache();
                DigestScheme digestScheme = new DigestScheme();
                authCache.put(target, digestScheme);    
                localContext.setAuthCache(authCache);
    
                // Tell the HTTP server that we will close the connection after the response
                request.addHeader("Connection", "close");
    
                // http response
                final HttpServiceResponse response = new HttpServiceResponse();
    
                // Execute the method.
                CloseableHttpResponse closeableResponse = httpClient5.execute(request, localContext);
    

    ...记录

    ... sorry... I had to remove the logging. because of security conserns.
    

0 个答案:

没有答案